PHP
Secure PHP Contact Form Handler
Drop this behind any contact form and you instantly get CSRF protection, a honeypot field for basic bots, and tidy validation responses. Keeps things small, readable and easy to adapt.
Usage notes
Place this file as your form action endpoint (for example, /contact-submit.php) and wire it up to your existing front-end.
- On the page that shows your form, generate
$_SESSION['contact_csrf']and include it as a hiddencsrffield. - Add a hidden text input called
websiteand keep it visually hidden (screen readers can ignore it). Real users never see or fill it; bots usually do. - Post
name,emailandmessagefields to this endpoint. - Replace the commented
mail()call with PHPMailer or your mail provider when you want proper deliverability.
Responses are deliberately plain so you can output them directly, or wrap them in JSON for an AJAX flow.
Copy this snippet into your project
Use the full version for learning, or copy it without comments when you just want the bare code.
<?php
declare(strict_types=1);
session_start();
// CSRF token check
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
exit('Method not allowed');
}
$token = $_POST['csrf'] ?? '';
if (!$token || !hash_equals($_SESSION['contact_csrf'] ?? '', $token)) {
http_response_code(400);
exit('Invalid request');
}
// Honeypot field
if (!empty($_POST['website'])) {
// Likely a bot
http_response_code(200);
exit('OK');
}
$name = trim((string)($_POST['name'] ?? ''));
$email = trim((string)($_POST['email'] ?? ''));
$message = trim((string)($_POST['message'] ?? ''));
if ($name === '' || $email === '' || $message === '') {
http_response_code(422);
exit('Missing fields');
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(422);
exit('Invalid email');
}
// TODO: replace this with PHPMailer or your mail provider
$subject = 'New contact form message';
$body = "From: {$name} <{$email}>\n\n{$message}";
// mail('you@example.com', $subject, $body);
http_response_code(200);
echo 'Thanks, your message has been sent.';