PHP
Beginner
Updated 7h ago
Contact Form with PHP Backend
A complete contact form with PHP processing, email sending, and validation. Includes honeypot anti-spam field.
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = trim($_POST["name"] ?? "");
$email = trim($_POST["email"] ?? "");
$message = trim($_POST["message"] ?? "");
$honeypot = $_POST["website"] ?? "";
if (!empty($honeypot)) { die("Spam detected."); }
$errors = [];
if (empty($name)) $errors[] = "Name is required";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email required";
if (empty($message)) $errors[] = "Message is required";
if (empty($errors)) {
$to = "you@example.com";
$subject = "New contact from $name";
$headers = "From: $email\r\nReply-To: $email";
if (mail($to, $subject, $message, $headers)) {
echo "Thank you! We will get back to you soon.";
} else {
echo "Sorry, something went wrong.";
}
} else {
echo implode("<br>", $errors);
}
}
?>
<form method="POST">
<input type="text" name="name" placeholder="Your Name" required>
<input type="email" name="email" placeholder="Your Email" required>
<textarea name="message" placeholder="Message" required></textarea>
<input type="text" name="website" style="display:none" tabindex="-1" autocomplete="off">
<button type="submit">Send Message</button>
</form>
Technical Breakdown
Complete contact form with server-side validation, honeypot anti-spam, and email sending via PHP mail().
Pitfalls & Solutions
1. mail() not working on localhost - use PHPMailer. 2. Honeypot visible. 3. Not sanitizing output.
Common Questions
How do I test the contact form on localhost?
Use PHPMailer with SMTP instead of mail() which needs a mail server.
What is a honeypot field?
A hidden field that bots fill but real users never see. If filled, submission is rejected as spam.
Tags
#PHP
#Forms
#Email
#Anti-Spam