A safe PHP contact form that sends email

Intermediate  Nov 3, 2026

Validate, block header injection and save a copy in the database.

A safe PHP contact form that sends email
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

Danger: header injection

If a user's email or name goes into mail headers unchecked, they can add \r\n and inject extra headers such as Bcc: and send spam through your server.

Danger: header injection
Danger: header injection

Safe version

<?php
$name    = trim((string)($_POST['name'] ?? ''));
$email   = trim((string)($_POST['email'] ?? ''));
$message = trim((string)($_POST['message'] ?? ''));

$hasNewline = fn(string $s) => preg_match('/[\r\n]/', $s) === 1;

if ($name === '' || $message === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)
    || $hasNewline($name) || $hasNewline($email)) {
    exit('Please check the form.');
}

$headers = [
    'From' => 'website@yourdomain.com',        // your own domain
    'Reply-To' => $email,
    'Content-Type' => 'text/plain; charset=UTF-8',
];

$body = "Name: $name\nEmail: $email\n\n$message";
mail('you@yourdomain.com', 'Website message', $body, $headers);

Use your own domain in From, and the visitor's address in Reply-To. Many mail servers reject mail that claims to be from someone else's domain.

How the code in this section fits into the page.
How the code in this section fits into the page.

Extra protection

  • Add a hidden "honeypot" field that real users never fill, and ignore submissions where it has a value.
  • Add a CSRF token and a simple rate limit.
  • Save each message in a table too, in case email delivery fails.
The main points of this section.
The main points of this section.

Note

Shared hosting often limits mail(). If messages go to spam, send through your host's SMTP with a library such as PHPMailer.

More tutorials