Overview
Validated contact form starter with CSRF protection and safe output handling.
What this script does
This starter demonstrates the core implementation pattern. Adapt database fields, configuration and error handling to your application.
Source code
<?php
declare(strict_types=1);
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
$errors = [];
$name = trim((string)($_POST['name'] ?? ''));
$email = trim((string)($_POST['email'] ?? ''));
$message = trim((string)($_POST['message'] ?? ''));
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!hash_equals($_SESSION['csrf'], (string)($_POST['csrf'] ?? ''))) $errors[] = 'Invalid form token.';
if ($name === '' || mb_strlen($name) > 100) $errors[] = 'Enter a valid name.';
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Enter a valid email.';
if ($message === '' || mb_strlen($message) > 5000) $errors[] = 'Enter a message.';
if (!$errors) {
// Connect an authenticated SMTP mailer here (for example PHPMailer).
$name = $email = $message = '';
$_SESSION['csrf'] = bin2hex(random_bytes(32));
}
}
?>
<form method="post">
<input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['csrf'], ENT_QUOTES, 'UTF-8') ?>">
<input name="name" maxlength="100" required value="<?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>">
<input type="email" name="email" required value="<?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?>">
<textarea name="message" maxlength="5000" required><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></textarea>
<button>Send</button>
</form>
Download starter source: Download PHP Contact Form with Validation source
Installation and customization
- Review the code and required PHP extensions.
- Configure database and storage settings outside the public web root where applicable.
- Add authorization, rate limiting and logging for public-facing endpoints.
- Test valid, invalid and boundary inputs before deployment.
> This is a learning starter, not a complete production application. Apply the security and deployment requirements of your project.