IntermediateLesson 8 of 16
Forms, GET & POST – PHP
Receiving input, validating it, outputting it safely and finishing with Post/Redirect/Get.
Form data arrives in the superglobals $_GET (URL parameters) and $_POST (form body). These arrays always contain unchecked user input. The flow is always: receive, validate, process, output safely.
<?php
// formular.php
$fehler = [];
$name = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
if ($name === "") {
$fehler[] = "Please enter a name.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$fehler[] = "Invalid email address.";
}
if (!$fehler) {
// ... save (e.g. via PDO) ...
header("Location: danke.php"); // Post/Redirect/Get
exit;
}
}
?>
<form method="post">
<input name="name" value="<?= htmlspecialchars($name) ?>">
<input name="email" type="email">
<button>Senden</button>
</form>
<?php foreach ($fehler as $f): ?>
<p class="fehler"><?= htmlspecialchars($f) ?></p>
<?php endforeach; ?>filter_input and filter_var check and convert values in one step:
<?php
$id = filter_input(INPUT_GET, "id", FILTER_VALIDATE_INT);
if ($id === false || $id === null) {
http_response_code(400);
exit("Invalid ID");
}
$seite = filter_input(INPUT_GET, "seite", FILTER_VALIDATE_INT,
["options" => ["default" => 1, "min_range" => 1]]);
echo "ID $id, page $seite";TipPost/Redirect/Get: after a successful POST, always redirect with
header("Location: ...") and exit. Otherwise a browser reload submits the form again (double order!).WarningEvery output of user data into HTML must go through
htmlspecialchars() – including re-inserting it into the form. Checking in the browser (required, type="email") is only a convenience: an attacker bypasses it with a single curl call.$_GET– URL parameters, for search/filter/paging (idempotent)$_POST– form data, for changes$_SERVER["REQUEST_METHOD"]– which HTTP method was used?$_FILES– uploaded files$_COOKIEand$_SESSION– state between requests