Processing HTML Forms
PHP excels at handling HTML form submissions. Use htmlspecialchars() to prevent XSS attacks.
Example
<!-- form.html -->
<form method="POST" action="process.php">
<input type="text" name="name" required>
<input type="email" name="email" required>
<textarea name="message"></textarea>
<button type="submit">Send</button>
</form>
<?php
// process.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Sanitize input
$name = htmlspecialchars(trim($_POST['name'] ?? ''));
$email = filter_var($_POST['email'] ?? '', FILTER_SANITIZE_EMAIL);
$message = htmlspecialchars(trim($_POST['message'] ?? ''));
// Validate
$errors = [];
if (empty($name)) $errors[] = 'Name is required';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email';
}
if (empty($errors)) {
echo "Thank you, $name!";
} else {
foreach ($errors as $error) {
echo "<p class='error'>$error</p>";
}
}
}
?> 