Forms and POST Data
Forms are how visitors send data to your PHP code. A form in HTML collects input, and when it is submitted, the browser sends the data to the file named in the action attribute. PHP receives it in the superglobal arrays $_GET and $_POST.
The method attribute chooses the delivery. GET puts the data in the URL as query strings, visible and bookmarkable, and is fine for searches. POST hides the data in the request body and is the right choice for passwords, messages, and anything that changes data. PHP picks the matching array automatically.
You read submitted values by their input name: $_POST["username"] holds what the visitor typed into the field named username. The name attribute in HTML is the key, not the id. Missing fields cause notices, so check with isset() before reading.
Never trust submitted data. A visitor can send anything, including text that looks like HTML or code. When you output it back into a page, escape it with htmlspecialchars() so it prints as text instead of executing. This one habit prevents most beginner XSS mistakes.
The HTML side
The form needs a method and an action. The action is the PHP file that receives the data. Each input needs a name, because that is the key PHP looks for. A submit button sends the form.
<form method="post" action="welcome.php">
<label for="name">Your name</label>
<input type="text" id="name" name="username">
<button type="submit">Send</button>
</form>
The PHP side
In welcome.php, $_POST holds the submitted values. Validate before using: check the field exists and is not empty, then echo it back safely. The ?? operator provides a default when the key is missing.
<?php
$name = $_POST["username"] ?? "friend";
if ($name === "") {
$name = "friend";
}
echo "Hello, " . htmlspecialchars($name) . "!";
?>
Syntax
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$email = $_POST["email"] ?? "";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Thanks, email looks valid.";
} else {
echo "That email is not valid.";
}
}
?>
$_POST Keys Match name="", Not id
Form data uses name attribute, not id — id is for label, name is for submit.
<input name="email" id="email">
Good to know
- GET data arrives in $_GET, POST data in $_POST.
- The input name attribute is the key PHP reads.
- Check fields with isset() or the ?? default before use.
- Escape output with htmlspecialchars() before echoing it.