title: PHP Form Spam Prevention
body: <p>Please bear with me as I am a graphic designer with some coding knowledge, but not near as much as a developer. And after many hours of tinkering and asking Google, I've decided to ask y'all directly!</p>
  
  <p>I've been working on building a contact form for my website. So far so good, except for one thing. I would like to add a simple spam prevention field.</p>
  
  <p>I've added a field "spamcheck" with the question 6+2=? but I do not know how to code the PHP to require that the value specifically be 8. As long as the other fields are correctly filled out, the form will submit regardless of the number entered here despite any attempt to mess with the code (thus why you will see my $spamcheck variable but the current coding only requires that it have a value like the rest of the fields).</p>
  
  <p>I have included the PHP, the validation the PHP calls to, and the form. Apologies if the form has some excess code; I have tried many different versions of PHP form tutorials to no avail.</p>
  
  <p>And of course, thank you very much for your help! :)</p>
  
  <p>Here is the PHP code I have placed directly in the web page:</p>
  
  <pre><code>&lt;?php 
  define("EMAIL", "email@gmail.com");
  
  if(isset($_POST['submit'])) {
  
    include('validate.class.php');
  
    //assign post data to variables 
      $name = trim($_POST['name']);
      $email = trim($_POST['email']);
      $budget = trim($_POST['budget']);
      $deadline = trim($_POST['deadline']);
      $message = trim($_POST['message']);
      $spamcheck = trim($_POST['spamcheck']);
  
    //start validating our form
    $v = new validate();
    $v-&gt;validateStr($name, "name", 1, 50);
    $v-&gt;validateEmail($email, "email");
    $v-&gt;validateStr($budget, "budget");
    $v-&gt;validateStr($deadline, "deadline");
    $v-&gt;validateStr($message, "message", 1, 1000);
    $v-&gt;validateStr($spamcheck, "spamcheck");
  
    if(!$v-&gt;hasErrors()) {
         $from = "website.com"; //Site name
    // Change this to your email address you want to form sent to
    $to = "email@gmail.com"; 
    $subject = "Hello! Comment from " . $name . "";
  
    $message = "Message from " . $name . "
    Email: " . $email . " 
    Budget: " . $budget ."
    Deadline: " . $deadline ."
    Message: " . $message ."";
    mail($to,$subject,$message,$from);
  
  
      //grab the current url, append ?sent=yes to it and then redirect to that url
          $url = "http". ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
          header('Location: '.$url."?sent=yes");
  
      } else {
      //set the number of errors message
      $message_text = $v-&gt;errorNumMessage();       
  
      //store the errors list in a variable
      $errors = $v-&gt;displayErrors();
  
      //get the individual error messages
      $nameErr = $v-&gt;getError("name");
      $emailErr = $v-&gt;getError("email");
      $budgetErr = $v-&gt;getError("budget");
      $deadlineErr = $v-&gt;getError("deadline");
      $messageErr = $v-&gt;getError("message");
      $spamcheckErr = $v-&gt;getError("spamcheck");
  
    }//end error check
  }// end isset
    ?&gt;
  </code></pre>
  
  <p>This is the validate.class.php which it calls to:</p>
  
  <pre><code>&lt;?php
  class validate {
  
    public $errors = array();
  
     public function validateStr($postVal, $postName, $min = 1, $max = 1000) {
      if(strlen($postVal) &lt; intval($min)) {
        $this-&gt;setError($postName, ucfirst($postName)." is required.");
      } else if(strlen($postVal) &gt; intval($max)) {
        $this-&gt;setError($postName, ucfirst($postName)." must be less than {$max} characters long.");
      }
    }// end validateStr
  
     public function validateEmail($emailVal, $emailName) {
      if(strlen($emailVal) &lt;= 0) {
        $this-&gt;setError($emailName, "Please enter an Email Address");
      } else if (!preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/', $emailVal)) {
        $this-&gt;setError($emailName, "Please enter a Valid Email Address");
          }
    }// end validateEmail     
  
    private function setError($element, $message) {
      $this-&gt;errors[$element] = $message;
    }// end logError
  
  
    public function getError($elementName) {
      if($this-&gt;errors[$elementName]) {
        return $this-&gt;errors[$elementName];
      } else {
        return false;
      }
    }// end getError
  
    public function displayErrors() {
      $errorsList = "&lt;ul class=\"errors\"&gt;\n";
      foreach($this-&gt;errors as $value) {
        $errorsList .= "&lt;li&gt;". $value . "&lt;/li&gt;\n";
      }
      $errorsList .= "&lt;/ul&gt;\n";
      return $errorsList;
    }// end displayErrors
  
    public function hasErrors() {
      if(count($this-&gt;errors) &gt; 0) {
        return true;
      } else {
        return false;
      }
    }// end hasErrors
  
    public function errorNumMessage() {
      if(count($this-&gt;errors) &gt; 1) {
              $message = "There was an error sending your message!\n";
          } else {
              $message = "There was an error sending your message!\n";
          }
      return $message;
    }// end hasErrors
  
  }// end class
  ?&gt;
  </code></pre>
  
  <p>And here is the form html/php:</p>
  
  <pre><code>&lt;span class="message"&gt;&lt;?php echo $message_text; ?&gt;&lt;/span&gt;
     &lt;?php if(isset($_GET['sent'])): ?&gt;&lt;h2&gt;Your message has been sent&lt;/h2&gt;&lt;?php endif; ?&gt;
            &lt;form role="form" method="post" action="webpage.php#contact"&gt;
              &lt;div class="form-group"&gt;
                &lt;input type="text" name="name" class="form-control" id="name" value="&lt;?php echo htmlentities($name); ?&gt;" placeholder="Full Name" required&gt;
                &lt;label for="exampleInputName"&gt;&lt;i class="icon-tag"&gt;&lt;/i&gt;&lt;/label&gt;
                &lt;span class="errors"&gt;&lt;?php echo $nameErr; ?&gt;&lt;/span&gt;
                &lt;div class="clearfix"&gt;&lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                &lt;input type="email" name="email" class="form-control" id="email" value="&lt;?php echo htmlentities($email); ?&gt;" placeholder="Email" required&gt;
                &lt;label for="exampleInputEmail1"&gt;&lt;i class="icon-inbox"&gt;&lt;/i&gt;&lt;/label&gt;
                &lt;span class="errors"&gt;&lt;?php echo $emailErr; ?&gt;&lt;/span&gt;
                &lt;div class="clearfix"&gt;&lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                &lt;input type="text" name="budget" class="form-control" id="budget" value="&lt;?php echo htmlentities($budget); ?&gt;" placeholder="Budget" required&gt;
                &lt;label for="exampleInputBudget1"&gt;&lt;i class="icon-usd"&gt;&lt;/i&gt;&lt;/label&gt;
                &lt;span class="errors"&gt;&lt;?php echo $budgetErr; ?&gt;&lt;/span&gt;
                &lt;div class="clearfix"&gt;&lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                &lt;input type="text" name="deadline" class="form-control" id="deadline" value="&lt;?php echo htmlentities($deadline); ?&gt;" placeholder="Deadline" required&gt;
                &lt;label for="exampleInputDeadline"&gt;&lt;i class="icon-calendar"&gt;&lt;/i&gt;&lt;/label&gt;
                &lt;span class="errors"&gt;&lt;?php echo $deadlineErr; ?&gt;&lt;/span&gt;
                &lt;div class="clearfix"&gt;&lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="form-group textarea"&gt;
                &lt;textarea rows="6" name="message" class="form-control" id="message" value="&lt;?php echo htmlentities($message); ?&gt;" placeholder="Write Message" required&gt;&lt;/textarea&gt;
                &lt;label for="exampleInputMessage"&gt;&lt;i class="icon-pencil"&gt;&lt;/i&gt;&lt;/label&gt;
                &lt;span class="errors"&gt;&lt;?php echo $messageErr; ?&gt;&lt;/span&gt;
                &lt;div class="clearfix"&gt;&lt;/div&gt;
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                &lt;input type="text" name="spamcheck" class="form-control" id="spamcheck" value="&lt;?php echo htmlentities($spamcheck); ?&gt;" placeholder="Spam check: 6+2=?" required&gt;
                &lt;label for="exampleInputSpamCheck"&gt;&lt;i class="icon-lock"&gt;&lt;/i&gt;&lt;/label&gt;
                &lt;span class="errors"&gt;&lt;?php echo $spamcheckErr; ?&gt;&lt;/span&gt;
                &lt;div class="clearfix"&gt;&lt;/div&gt;
              &lt;/div&gt;
  
              &lt;button type="submit" id="submit" name="submit" value="submit" class="btn btn-large"&gt;Send Message&lt;/button&gt;
            &lt;/form&gt;
  </code></pre>