HTML forms send data to PHP through $_GET or $_POST. Always validate that data meets requirements and sanitize it before use. Use htmlspecialchars() when displaying user input and PDO prepared statements for database queries.
Processing HTML Forms
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Sanitize inputs
$name = htmlspecialchars(trim($_POST["name"] ?? ""));
$email = filter_input(INPUT_POST, "email", FILTER_VALIDATE_EMAIL);
$age = filter_input(INPUT_POST, "age", FILTER_VALIDATE_INT);
// Validate
$errors = [];
if (empty($name)) $errors[] = "Name is required";
if (!$email) $errors[] = "Valid email required";
if (!$age || $age < 18) $errors[] = "Must be 18+";
if (empty($errors)) {
// Save to database
echo "Success!";
}
}
?>
<form method="POST">
<input name="name" value="<?= htmlspecialchars($name ?? '') ?>">
<input name="email" type="email">
<input name="age" type="number">
<button type="submit">Submit</button>
</form>