A simple contact form and the PHP handler in the same file:
<?php
$error = "";
$message = "";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
if ($name === "" || $email === "") {
$error = "Name and email are required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error = "Invalid email address.";
} else {
$message = "Thanks, " . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "!";
}
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if ($error): ?><p style="color:red"><?= $error ?></p><?php endif; ?>
<?php if ($message): ?><p><?= $message ?></p><?php endif; ?>
<form method="post">
<input name="name" placeholder="Your name" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>">
<input name="email" placeholder="Your email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
<button type="submit">Submit</button>
</form>
</body>
</html>
Critical rule: always use htmlspecialchars() when echoing user input back to the browser to prevent Cross-Site Scripting (XSS) attacks. Never trust data from $_GET, $_POST, or $_COOKIE.