The "Spicy" checkbox on the order form is left unticked. Then PHP suddenly prints a warning: Warning: Undefined array key "spicy". Yet the field (the input box) is right there in the form. Forms don't work quite the way you'd think. This lesson follows what a visitor types all the way from the browser to PHP.
A form is how the browser sends what a visitor typed to the server, and PHP receives it as an array. Picture the order slip at Mrs. Tini's Stall. The customer fills in the dish, the quantity and a note, then the slip is carried to the kitchen. The slip can travel open, so anyone passing by can read it. That's GET: the fields are attached to the URL. The slip can also travel inside an envelope. That's POST: the fields are sent in the request body (the part of the request that doesn't show in the address). In the kitchen, Mrs. Tini doesn't trust the slip right away. She checks that the dish exists and that the quantity makes sense. PHP has to check every field before it uses it, too.
The form sends, PHP receives
This is the order form:
<form method="post" action="order.php">
<select name="menu">
<option>Fried Rice</option><option>Chicken Noodles</option><option>Iced Tea</option>
</select>
<input name="quantity" value="1">
<input name="note">
<label><input type="checkbox" name="spicy" value="yes"> Spicy</label>
<button>Order</button>
</form>
The customer picks Fried Rice, types 2 as the quantity, ticks Spicy and presses Order. The browser sends this request to order.php:
POST /order.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded
menu=Fried+Rice&quantity=2¬e=&spicy=yes
The last line is the request body: each field is written as name=value, separated by &, and a space is written as +.
In order.php, those fields have already become the array $_POST. print_r($_POST); prints what is inside:
Array
(
[menu] => Fried Rice
[quantity] => 2
[note] =>
[spicy] => yes
)
- Each field's
nameattribute becomes a key in the array, and what the customer entered becomes its value. - Every value is a string. The quantity is
"2", not the number2. $_POSTand$_GETare called superglobals: built-in PHP arrays you can read from anywhere in the script.- If you change
method="post"tomethod="get", the same fields move into the URL:order.php?menu=Fried+Rice&quantity=2¬e=&spicy=yes. PHP puts them in$_GET, and$_POSTstays empty.
| GET | POST | |
|---|---|---|
| Fields travel in | the URL (query string, the part after ?) |
the request body |
| PHP reads them from | $_GET |
$_POST |
| Fits | reading: search the menu, page 2 | changing data: order, sign up, log in |
| On refresh | safe, it only reads again | the browser asks whether to send it again |
Fields that never arrive: ?? and isset
An unticked checkbox is not sent at all. The request has no spicy=, so the key spicy doesn't exist in $_POST either. If you read that key directly:
$spicy = $_POST["spicy"];
PHP prints:
Warning: Undefined array key "spicy" in /var/www/stall/order.php on line 17
The value isn't "" and isn't false. The key really doesn't exist, so PHP prints a Warning, and $spicy holds null. (Line 17 is that line in the full order.php, which is in the Lab.) An emptied text input is different: it is still sent (note=). So $_POST["note"] exists, and it holds "".
This is the safe way to read the fields:
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$menu = $_POST["menu"] ?? "";
$note = $_POST["note"] ?? "";
$spicy = isset($_POST["spicy"]);
}
$_SERVERis a superglobal with information about the request.$_SERVER["REQUEST_METHOD"]holds"GET"or"POST". A page that has just been opened is always GET. With thisif, the form is only processed when it really was sent with POST.??(null coalescing) uses the value on the right when the key on the left is missing or holdsnull. No Warning.isset($_POST["spicy"])answerstruewhen the key exists and its value isn'tnull. So$spicyistruewhen Spicy is ticked, andfalsewhen it isn't.empty($_POST["note"])answerstruewhen the key is missing or its value counts as empty:"","0",0ornull. Careful,empty("0")istruetoo.
Several choices at once. For several checkboxes with the same name, such as toppings, add [] to the end of the name: <input type="checkbox" name="topping[]" value="Egg">. The Cheese and Sausage checkboxes are written the same way. If the customer ticks Egg and Sausage, $_POST["topping"] holds the array ["Egg", "Sausage"]. Without [], PHP keeps only the last value: "Sausage". When nothing is ticked, the key topping doesn't exist, so read it with $_POST["topping"] ?? [] (an empty array).
Validation: check every field before using it
Required fields are checked one by one with a loop, not with an if written again for each field. The first line fills $_POST by hand as example input. That way the code can run without a form:
$_POST = ["name" => "Budi", "email" => "", "message" => "Hello!"];
$valid = true;
foreach (["name", "email", "message"] as $field) {
if (empty($_POST[$field])) {
echo "Error: $field is required\n";
$valid = false;
}
}
if ($valid) {
echo "Thank you, " . $_POST["name"] . "! Message received.";
}
// Error: email is required
For a field that must be a number or an email, PHP has built-in filters. This code reads quantity and accepts only a whole number from 1 to 20:
$quantity = filter_input(INPUT_POST, "quantity", FILTER_VALIDATE_INT, [
"options" => ["min_range" => 1, "max_range" => 20],
]);
quantity entered |
Result |
|---|---|
2 |
int(2) |
3 (with spaces) |
int(3) |
two, 2.5, 25, 0 |
false |
| field not sent | null |
filter_inputreads straight from the request, not from the$_POSTarray. When you fill$_POSTyourself (as in the exercise),filter_inputdoesn't see what you put there, so usefilter_var($_POST["quantity"], FILTER_VALIDATE_INT, ...)with the same rules.FILTER_VALIDATE_EMAILchecks an email:"[email protected]"is accepted,"budi@mail"givesfalse.- Server-side validation is required, even when the form has
requiredortype="number". A request can be sent without going through your form at all, so the checks in the HTML can be skipped.
Uploading a file, for example a photo of a payment receipt. The form needs enctype="multipart/form-data" (a way of sending that can carry files) and <input type="file" name="receipt">. The file arrives in $_FILES["receipt"], not in $_POST. This code checks the file, then saves it:
$file = $_FILES["receipt"] ?? null;
if (!$file || $file["error"] !== UPLOAD_ERR_OK) {
exit("The upload failed. Please try again.");
}
$types = ["image/jpeg" => "jpg", "image/png" => "png"];
$type = mime_content_type($file["tmp_name"]);
if ($file["size"] > 2 * 1024 * 1024 || !isset($types[$type])) {
exit("The photo must be a JPG or PNG, 2 MB at most.");
}
$name = bin2hex(random_bytes(8)) . "." . $types[$type];
move_uploaded_file($file["tmp_name"], __DIR__ . "/uploads/$name");
echo "Payment receipt received.";
exit("...")prints that message, then stops the script.- PHP keeps the uploaded file in a temporary folder. Its location is in
tmp_name, and the file is deleted when the script ends, unlessmove_uploaded_filemoves it. mime_content_typereads the file type from the file's content. The file name and$_FILES["receipt"]["type"]are written by the sender's browser, so they can be faked.- The new name is random, so a visitor can't choose a name like
receipt.php(the server could run a.phpfile as code).
Output: htmlspecialchars every time you print input
Say the customer writes the note <b>spicy</b>. If that note is echo-ed as it is, the browser reads it as a tag. A note holding <script> is more dangerous: the code inside it runs in the browser of anyone else who opens that page, as if the code were part of your website. This attack is called XSS (cross-site scripting). The safe way:
echo "<p>Note: " . htmlspecialchars($note) . "</p>";
// <p>Note: <b>spicy</b></p>
htmlspecialcharsturns<>&"', in that order, into<>&"'. The browser shows them as text and opens no tag.- From PHP 8.1 on, the default flags (settings) already include
ENT_QUOTES, and the charset is UTF-8. So for ordinary text,htmlspecialchars($input)gives the same result as thehtmlspecialchars($input, ENT_QUOTES, "UTF-8")you often see in older code. - Changing those characters is called escaping. Escape at output, at the moment the input is written into the page. The details are in the lesson XSS Prevention & Sanitization in the Security track.
💡 POST/Redirect/GET
Say order.php writes "Order received" right after the order is saved. If the customer then presses refresh, the browser sends the same POST again, and the same order is saved twice. The pattern: save the order, then tell the browser to move to another page with GET. In this code, saveOrder() saves the order and returns its number:
$id = saveOrder($menu, $quantity, $note, $spicy);
header("Location: order.php?id=$id", true, 303);
exit;
header("Location: ...", true, 303)answers with the status303 See Otherand the address to go to. If the number is 1, the browser opensorder.php?id=1with GET right away.- Without
exit, the code below it keeps running. - A refresh now only repeats the GET that shows order #1. No new order.
A POST form that changes data also needs a CSRF token, to prevent CSRF: another site quietly sends a form to your stall on behalf of a customer who is logged in. The token is a random value in a hidden input. The server checks it against the value kept in the session (one visitor's data on the server, explained in the lesson Password Hashing & Sessions). The other site doesn't know that value, so its fake form is refused. How to do it is in the lesson CSRF (Cross-Site Request Forgery) in the Security track.
⚠️ Don't trust form input as it is
- Reading a key that may be missing.
$_POST["spicy"]from an unticked checkbox givesWarning: Undefined array key "spicy". Useissetor??. - Trusting input because the HTML validates it.
requiredandtype="number"can be skipped. Check again in PHP withempty,filter_varorfilter_input. echo $_POST["comment"];without escaping. That's an XSS hole. Wrap it inhtmlspecialchars().- Writing one
ifper field. Required fields are checked with aforeachover a list of field names, so a new field just goes into the list.
TL;DR: A form sends its fields to PHP as an array. With method="get", the fields travel in the URL and land in $_GET. With method="post", they travel in the request body (the part that doesn't show in the address) and land in $_POST. The keys come from the name attribute, and the values are always strings. An unticked checkbox isn't sent, so reading it directly gives Warning: Undefined array key. Read fields with isset() or ??, and first check $_SERVER["REQUEST_METHOD"] === "POST" (the form really was sent with POST). Validate (check) every field on the server: foreach + empty for required fields, filter_input/filter_var with FILTER_VALIDATE_INT for numbers. Print input into the page through htmlspecialchars(), so it can't become XSS (a visitor's code running in other people's browsers). After a successful POST, redirect (tell the browser to open another page with GET) with header("Location: ...", true, 303); exit;, so a refresh doesn't resend it. A POST form that changes data also needs a CSRF token (a random value that proves the form came from your own page).
⚡ The form sends, PHP receives an array
Guess first: a form is sent with POST, and PHP receives its fields in the array $_POST. A visitor types 2 in the quantity field. In $_POST, is it the number 2 or the string "2"?
The string "2". Every form field reaches PHP as a string.
Meaning: Each field's name attribute becomes an array key, and what the visitor entered becomes its value. A form with method="get" sends its fields in the URL, and PHP puts them in $_GET. A form with method="post" sends them in the request body (the part that doesn't show in the address), and PHP puts them in $_POST.
⚡ An unticked checkbox isn't sent
Write:
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$menu = $_POST["menu"] ?? "";
$note = $_POST["note"] ?? "";
$spicy = isset($_POST["spicy"]);
}
Meaning: An unticked checkbox isn't sent, so its key doesn't exist in $_POST. Reading $_POST["spicy"] directly gives Warning: Undefined array key. ?? uses the value on its right when the key is missing, and isset() answers true only when the key exists. The first if line makes sure the form really was sent with POST.
⚡ Validate every field with a loop
Write:
$valid = true;
foreach (["name", "email", "message"] as $field) {
if (empty($_POST[$field])) {
echo "Error: $field is required\n";
$valid = false;
}
}
Meaning: Validation means checking the fields before you use them. foreach walks through the list of required field names, and empty() answers true when that field is missing or empty. Server-side validation is still required, even when the form has required (a check in the HTML), because a request can be sent without going through your form.
⚡ Input is printed through htmlspecialchars
Write:
echo "<p>Note: " . htmlspecialchars($note) . "</p>";
Meaning: htmlspecialchars turns the < and > in $note into < and >. So a note holding <script> shows as text. Without htmlspecialchars, the code inside that <script> runs in the browser of anyone else who opens the page. This attack is called XSS.