Database design: keys, relationships and normalization
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
Validate, block header injection and save a copy in the database.
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.
<?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.
Shared hosting often limits mail(). If messages go to spam, send through your host's SMTP with a library such as PHPMailer.
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
A folder layout and a few habits that keep a growing PHP site tidy, secure and easy to maintain.