PHP Project: Contact Form

A contact form with validation on both sides: jQuery checks the fields in the browser, and PHP re-checks them on the server (required fields and a valid email address) before sending the message with PHP's mail() function.

The form

The PHP behind it

Server-side validation and sending:

<?php

      $error = "";
      $succcessMessage = "";

    if ($_POST) {

      if (!$_POST["email"]) {

        $error .= "An email address is required.<br>";
      }

      if (!$_POST["subject"]) {

        $error .= "Please include a subject heading.<br>";
      }

      if (!$_POST["textArea"]) {

        $error .= "Please include some content<br>";
      }

      if ($_POST["email"] && filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
          $error .= "The email address is invalid.<br>";

        }
      if ($error != "") {
        $error = '<div class="alert alert-danger" role="alert">There were errors in your form: <br>'. $error .'</div>';


      }  else {
            $emailTo = "you@example.com";
            $subject = $_POST["subject"];
            $textArea = $_POST["textArea"];
            $headers = "From: ".$_POST["email"];

            if (mail($emailTo, $subject, $textArea, $headers)) {
              $succcessMessage = '<div class="alert alert-success" role="alert">Your message was sent and I\'ll get back to you ASAP.</div>';

            } else {
              $error = '<div class="alert alert-danger" role="alert">Your message couldn\'t be sent, please try again.</div>';


            }

      }

    }


 ?>