The contact form is the most common piece of PHP on small websites – and one of the most abused. This guide shows a compact, safe approach. It assumes a supported PHP version and builds on HTML form validation.
The HTML
<form action="contact.php" method="post">
<label for="name">Name</label>
<input id="name" name="name" required maxlength="100" autocomplete="name">
<label for="email">Email</label>
<input id="email" name="email" type="email" required maxlength="200" autocomplete="email">
<label for="message">Message</label>
<textarea id="message" name="message" required minlength="10" maxlength="3000"></textarea>
<!-- honeypot: hidden from people, bots fill it in -->
<div hidden><label>Leave empty <input name="website" tabindex="-1" autocomplete="off"></label></div>
<button>Send</button>
</form>The PHP
<?php
declare(strict_types=1);
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }
// 1. Honeypot: bots fill in hidden fields
if (!empty($_POST['website'])) { exit('Thank you!'); }
// 2. Validate
$name = trim((string)($_POST['name'] ?? ''));
$email = trim((string)($_POST['email'] ?? ''));
$message = trim((string)($_POST['message'] ?? ''));
$errors = [];
if ($name === '' || mb_strlen($name) > 100) $errors[] = 'Please enter your name.';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Please enter a valid email address.';
if (mb_strlen($message) < 10 || mb_strlen($message) > 3000) $errors[] = 'Please write a message of 10 to 3000 characters.';
// 3. Never allow line breaks in values used in headers
if (preg_match('/[\r\n]/', $name . $email)) $errors[] = 'Invalid input.';
if ($errors) {
http_response_code(422);
echo implode('<br>', array_map('htmlspecialchars', $errors));
exit;
}
// 4. Send (better: use an SMTP library with your domain account)
$body = "Name: $name\nEmail: $email\n\n$message";
$headers = ['From' => 'website@example.com', 'Reply-To' => $email];
mail('info@example.com', 'Website contact form', $body, $headers);
echo 'Thank you! We will reply within one working day.';Security checklist
- Escape anything you show back to the browser with
htmlspecialchars(). - Use a fixed
Fromaddress on your own domain; put the visitor’s address inReply-To. - Add rate limiting (for example per IP address per hour) to stop floods.
- Serve the form over HTTPS.
- Mention the form in your privacy statement and do not store messages longer than needed.
Frequently asked questions
Why do my form emails end up in spam?
Often because they are sent by the web server without proper authentication. Use an SMTP account on your domain, and set up SPF, DKIM and DMARC.
Should I use CAPTCHAs?
Start without them. A honeypot and rate limiting stop most bots without annoying visitors. Add a privacy-friendly challenge only if spam continues.