Processing Forms
Processing a form means reading the values a submitted form sent and using them in a program. The values arrive as text in the $_POST array.
A welcome card from two fields
Two lines fill $_POST by hand with a name and a city. trim cuts the stray spaces from each value before the card prints.
<?php
$_POST["name"] = " Hana ";
$_POST["city"] = " Oslo ";
$name = trim($_POST["name"]);
$city = trim($_POST["city"]);
echo "Welcome, " . $name . "\n";
echo "City: " . $city . "\n";A missing field prints a fallback
Only the name field is filled here. isset finds no plan key, so the else branch prints the fallback line.
<?php
$_POST["name"] = "Hana";
if (isset($_POST["plan"])) {
echo "Plan: " . $_POST["plan"] . "\n";
} else {
echo "Plan: Not chosen\n";
}Three fields in a summary
Three fields are filled by hand here. Each value reads out by its key and prints on its own summary line.
<?php
$_POST["name"] = "Mina";
$_POST["city"] = "Bergen";
$_POST["message"] = "See you soon";
echo "Name: " . $_POST["name"] . "\n";
echo "City: " . $_POST["city"] . "\n";
echo "Message: " . $_POST["message"] . "\n";Example
<?php
$_POST["name"] = "Omar";
$_POST["email"] = "omar@example.com";
$_POST["plan"] = "Premium";
echo "Name: " . $_POST["name"] . "\n";
echo "Email: " . $_POST["email"] . "\n";
echo "Plan: " . $_POST["plan"] . "\n";Key points
- A server fills $_POST from the submitted form before the code runs, and the lessons here fill that array by hand to show its shape.
- Reading a field uses the field name as the key in $_POST.
- trim cuts spaces from both ends of a string.
- Form values often carry stray spaces, so trimming a value before use is a common first step.
- isset checks that a field is present before the program reads it.
- A missing field guarded by isset can print a fallback line instead of failing.
In this example, three lines fill $_POST by hand with the fields of a signup form. The print lines read each field by its key. The summary shows the name, the email address and the plan on three lines.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Why does a program check a $_POST field with isset before reading it?