#StackBounty: #php #html PHP Captcha showing error message even when captcha is enter correctly

Bounty: 50

I have created a contact form that once the user enters their details and clicks submit the details they have entered are sent to my email. The form works well and the emails are being sent, however I noticed that I would receive a lot of spam emails from the contact form. I decided that the best way to stop the the spam would be to add a captcha so that the user must enter the letters within the captcha image before the form can be submitted.

I have been able to get the captcha image to display, however even if the captcha is not entered correctly the form still seems to submit.

Here is my contact form code

<?php

  if (isset($_POST["submit"])) {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    $captcha = $_POST['captcha-input'];

    $from= 'From:' . $name .  "rn" .'Reply-To:' . $email . "rn" .'X-Mailer: PHP/' . phpversion();

    $to = 'example@yahoo.com'; 
    $subject = 'Message from example.com';
    $body = "$message";

    
    if (!$_POST['name']) {
      $errorName = 'Please enter your name';
    }
    
  
    if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
      $errorEmail = 'Please enter a valid email address';
    }
    
    
    if (!$_POST['message']) {
      $errorMessage = 'Please enter your message';
    }

    if (!$_POST['captcha-input'] || filter_var($_POST['captcha-input'], FILTER_SANITIZE_STRING)) {
      $errorCaptcha = 'Please enter the captcha';
     } 
    
    if ($_SESSION['CAPTCHA_CODE'] !== $captchaUser) {
      $result = '<div id="error" class="error">CAPTCHA has failed</div>';
  } else if (!$errorName && !$errorEmail && !$errorMessage) {
     if (mail ($to, $subject, $body, $from)) {
         $result='<div id="success" class="success">Thank You! I will be in touch</div>';
       } else {
         $result='<div class="error">Sorry there was an error sending your message. </div>';
       }
       $_POST = array();
   }
  }


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.