How to create a PHP contact form Print

  • 0

The simplest reliable option is a form plugin (for WordPress) or a library such as PHPMailer that sends through SMTP. If you need a basic hand-written form, this example shows the essentials.

form.html

<form action="send.php" method="post">
  <input type="text" name="name" required placeholder="Your name">
  <input type="email" name="email" required placeholder="Your email">
  <textarea name="message" required></textarea>
  <button type="submit">Send</button>
</form>

send.php

<?php
$name    = strip_tags(trim($_POST['name'] ?? ''));
$email   = filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL);
$message = strip_tags(trim($_POST['message'] ?? ''));

if (!$name || !$email || !$message) { exit('Please complete all fields.'); }

$to      = 'enquiries@yourdomain.co.uk';
$subject = 'Website enquiry from ' . $name;
$headers = "From: website@yourdomain.co.uk\r\nReply-To: $email\r\n";

mail($to, $subject, $message, $headers, '-fwebsite@yourdomain.co.uk');
echo 'Thank you, your message has been sent.';

Important

  • The From address must be a real mailbox on your own domain, and the fifth parameter (-f) must use it. Never use the visitor's address as From; put it in Reply-To.
  • Add spam protection such as reCAPTCHA or a honeypot field.
  • For better delivery, send via SMTP (see PHP mail() vs SMTP).

Was this answer helpful?

« Back