Build a Contact Form with Validation and Email Sending in PHP

Why Build a Contact Form?

A contact form is a standard feature on almost every website. It allows visitors to:

  • Ask questions
  • Request services
  • Send feedback
  • Report issues

PHP’s built-in mail() function makes it easy to send messages from the site owner to their email inbox, without needing a backend framework.

Folder Structure πŸ—‚οΈ

Plaintext
project/
β”œβ”€β”€ contact.html
└── send.php

Step 1: Create the HTML Contact Form

contact.html

HTML
<form action="send.php" method="post">
  <label>Your Name:</label><br>
  <input type="text" name="name" required><br><br>

  <label>Your Email:</label><br>
  <input type="email" name="email" required><br><br>

  <label>Subject:</label><br>
  <input type="text" name="subject" required><br><br>

  <label>Message:</label><br>
  <textarea name="message" rows="5" required></textarea><br><br>

  <input type="submit" value="Send Message">
</form>

Step 2: Validate and Send Using PHP

send.php

PHP
<?php
function clean($input) {
  return htmlspecialchars(strip_tags(trim($input)));
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $name = clean($_POST['name']);
  $email = clean($_POST['email']);
  $subject = clean($_POST['subject']);
  $message = clean($_POST['message']);

  $errors = [];

  // Validation
  if (!$name || strlen($name) < 2) {
    $errors[] = "Name must be at least 2 characters.";
  }

  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Invalid email format.";
  }

  if (!$subject || strlen($subject) < 3) {
    $errors[] = "Subject must be at least 3 characters.";
  }

  if (!$message || strlen($message) < 10) {
    $errors[] = "Message must be at least 10 characters.";
  }

  // If no errors, send email
  if (empty($errors)) {
    $to = "you@example.com"; // Replace with your email
    $body = "Name: $name\nEmail: $email\n\nMessage:\n$message";
    $headers = "From: $name <$email>\r\n";

    // Send email
    if (mail($to, $subject, $body, $headers)) {
      echo "<p style='color:green;'>Your message has been sent successfully!</p>";
    } else {
      echo "<p style='color:red;'>Failed to send email. Try again later.</p>";
    }
  } else {
    foreach ($errors as $error) {
      echo "<p style='color:red;'>$error</p>";
    }
  }
}
?>

Features Included

  • Basic input sanitization using strip_tags() and htmlspecialchars()
  • Email format validation using filter_var()
  • Minimum character checks for name, subject, and message
  • Custom success/error messages
  • Prevention of basic spam techniques like header injection

Advanced Tips (Optional Enhancements)

  • Use Google reCAPTCHA to block bots
  • Replace mail() with PHPMailer or SMTP for higher email delivery rates
  • Store form data to a database or log file
  • Add AJAX to submit the form without reloading the page

Common Mistakes to Avoid

  • Not validating email format
  • Allowing HTML tags in input (XSS vulnerability)
  • Forgetting to sanitize subject/message before using them in headers
  • Using mail() without fallback or logging for errors

Best Practices

  • Validate every input field on the server side
  • Sanitize all user inputs before using or storing them
  • Never use raw $_POST directly in mail()
  • Store backup logs of messages if email fails
  • Keep user-facing messages friendly and non-technical

Notes:

  • You can easily build a working contact form with PHP using HTML and the mail() function
  • Validation and sanitization are essential to ensure reliability and security
  • Provide clear messages to users after form submission
  • Consider improving the reliability of email delivery using a library or SMTP provider

Practice Tasks

Task 1: Add Phone Number Field
Add a phone number input to the form. Validate it with a regular expression and include it in the email body.

Task 2: Build a Service Request Form
Create a form for service selection (like β€œWeb Design”, β€œSEO”, etc.), using a dropdown. Include the selected service in the message sent via email.

Task 3: Send a Confirmation Email
Use mail() to send a confirmation back to the user’s email address thanking them for their message.