Question

i have a simple contact form that i have included a honeypot input field. i would like the form to redirect to a webpage if the field is filled out.

i tried the below code, but it is giving me an error: the AJAX request failed!

so i know i have done something wrong. i'm sure it is simple.

thanks

the php code:

    if(!empty($_POST["e-mail"])) header('Location: blankman.html');exit;

the form input:

    <input type="text" name="e-mail" id="e-mail"/>

here is the full php code:

    <?php

if(!empty($_POST["e-mail"])) header('Location: blankman.html');exit;

// Clean up the input values
foreach($_POST as $key => $value) {
  if(ini_get('magic_quotes_gpc'))
    $_POST[$key] = stripslashes($_POST[$key]);

  $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}

// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];


// Test input values for errors
$errors = array();
if(strlen($name) < 2) {
  if(!$name) {
    $errors[] = "missing your name";
  } else {
    $errors[] = "your name must be 2 characters";
  }
}

if(!$email) {
  $errors[] = "missing your email";
} else if(!validEmail($email)) {
  $errors[] = "you must enter a valid email";
}
if(strlen($message) < 3) {
  if(!$message) {
    $errors[] = "missing your message";
  } else {
    $errors[] = "oops! your message is not long enough";
  }
}

if($errors) {
  // Output errors and die with a failure message
  $errortext = "";
  foreach($errors as $error) {
    $errortext .= "<li>".$error."</li>";
  }
$response = array(
    "success" => false,
    "content" => "<span class='failure'><ul>". $errortext ."</ul></span>"
);
die(json_encode($response));
}

// Send the email *********** enter your email address and message info ***
$to = "myemail@myemail.com"; 
$subject = "Website message from: $name";
$message = "From:\n$name\n\nEmail:\n$email\n\nMessage:\n$message";
$headers = "From: $email";

mail($to, $subject, $message, $headers);

// Die with a success message
$response = array(
    "success" => true,
    "content" => "<span class='success'><li>Thank you! Your message has been sent :).</li></span>"
);
die(json_encode($response));

// A function that checks to see if
// an email is valid
function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

?>

here is the javascript:

<script>
    $(document).ready(function () {
        $("#contactform").submit(function (e) {
            e.preventDefault();
            var t = $(this).attr("action");
            var n = $(this).serialize();
            $.post(t, n, null, "json").done(function (e) {
                if (e.success) {
                    $("#success").html(e.content);
                    $("#contactform,#error").hide()
                } else {
                    $("#error").html(e.content)
                }
            }).fail(function () {
                alert("The AJAX request failed!")
            })
        })
    })
</script>
Was it helpful?

Solution

Do not show whatever different behavior if honeypot is filled. This way you are screaming to a spamer with BIG RED LETTERS: "Here is a honeypot! Investigate and write a workaround!"

Always respond to a spam request EXACTLY the same way as to a regular one:

if(!empty($_POST["e-mail"])) {
    $response = array(
        "success" => true,
        "content" => "<span class='success'><li>Thank you! Your message has been sent :).</li></span>"
    );
    die(json_encode($response));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top