$_POST and Processing a Form
A visitor fills in Pageturn's order form: book, quantity, email. Those details must not sit in a bookmarkable URL, and submitting them creates an order. That is a job for POST, and every PHP form follows the same short recipe.
The rule
Check the method, validate every field, act, then redirect.
The form:
<form method="post" action="order.php">
<input name="title" value="Dune">
<input name="qty" type="number" value="1">
<input name="email" type="email">
<button>Order</button>
</form>Each input's name becomes a key in $_POST. The data travels in the request body, not the URL. The script:
<?php
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$qty = filter_var($_POST['qty'] ?? '', FILTER_VALIDATE_INT);
$email = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
if ($qty === false || $qty < 1) {
$errors[] = 'Quantity must be a whole number of at least 1.';
}
if ($email === false) {
$errors[] = 'Please enter a valid email address.';
}
if (!$errors) {
saveOrder($_POST['title'], $qty, $email);
header('Location: thanks.php'); // redirect after success
exit;
}
}
// otherwise show the form again, with $errors escaped and listedThe recipe, step by step:
- Check the method. The same script often shows the form (GET) and handles it (POST).
$_SERVER['REQUEST_METHOD']tells you which. - Validate every field. Like
$_GET,$_POSTis text sent by the visitor, and it can be missing or crafted by hand.filter_varreturns the clean value, orfalsewhen it does not fit. Browser checks such astype="email"help honest visitors but stop no one else. - Act only when there are no errors.
- Redirect. Send a
Locationheader andexit. Without this, pressing Refresh on the result page resubmits the form and orders a second copy. This pattern is called Post/Redirect/Get.
When validation fails, show the form again with the messages, escaping everything you print back with htmlspecialchars().
The shortcut
Say the four words as you write the handler: method, validate, act, redirect. A missing word is a missing safety step.
Method
The request is a POST, so the handler runs.
Drills
Answer fast — trust the rule.
Where does a POST form's data travel?
An input is written <input name="qty">. How does PHP read it after a POST?
What does filter_var("3", FILTER_VALIDATE_INT) return?
Why redirect after a successful order?
The form uses type="email". Do you still need server-side validation?
Remember
- Check the method, validate every field, act, then redirect.
- Shortcut: say "method, validate, act, redirect" while writing the handler.
- Trap: browser validation is a courtesy, not security; the server must check again.
