Handling Forms ($_POST & $_GET)
The heart of PHP: receive data from HTML forms and respond. This is where dynamic sites begin.
What you will learn
- Receive form data with $POST and $GET
- Connect an HTML form to a PHP script
- Display submitted data
Form → PHP
An HTML form’s action points to a PHP file, and method decides how the data arrives: POST → $_POST, GET → $_GET. Each field’s name becomes the array key. ($_POST and $_GET are special built-in arrays — called *superglobals* — that PHP fills in for you with the submitted data.)
Here is the whole journey, start to finish, so you can picture how a click in the browser ends up as data in PHP:
- The user fills in the form fields and clicks the submit button.
- The browser bundles up each field by its
nameand sends them to the file inaction(heresubmit.php). - Because
method="post", PHP places those values into the$_POSTarray, keyed by each field’sname. submit.phpruns, reads the values out of$_POST, and builds an HTML response.- The server sends that HTML back, and the browser shows the result to the user.
First, the HTML form. Each input has a name — that name is the label PHP will use to find the value later:
<!-- index.html (or .php) -->
<form action="submit.php" method="post">
<input type="text" name="username">
<input type="email" name="email">
<button type="submit">Send</button>
</form>The action="submit.php" says where to send the data, and method="post" says to send it hidden in the request body. The two inputs are named username and email — keep those names in mind, because the PHP file uses them as keys.
Now the PHP file that receives it. It pulls each value out of $_POST using the matching field name:
<!-- submit.php -->
<?php
$name = $_POST["username"];
$email = $_POST["email"];
echo "Thank you, $name! We will email $email.";
?>$_POST["username"] grabs whatever the user typed in the field named username and stores it in $name; the email line does the same. The echo then builds a friendly reply using those values.
Note: Output (if the user typed "Asha" and "asha@x.com"):
Thank you, Asha! We will email asha@x.com.
The key inside $_POST[...] matched the form field’s name exactly, so PHP found the right value. Change the field name without changing the PHP key and it would break.
Watch out: The $_POST key must exactly match the form field’s name attribute. name="username" → $_POST["username"]. A mismatch gives an “undefined index” warning.
Tip: Recall from the HTML course: use POST for logins and anything sensitive (data hidden in the request body), and GET for searches (data visible in the URL).
Q. A form field named "email" submitted with POST is read in PHP as:
✍️ Practice
- Build an HTML form that posts to a PHP file which greets the user by name.
- Add an email field and display both values.
🏠 Homework
- Build a contact form (name, email, message) where the PHP page confirms the submission.