-2

I have a simple contact form. Works great - except the several emails I get daily. Spam!! I want to add a simple verification question (such as 'Zebras are black and...') where only a certain answer its accepted or the form will not be sent. How do I go about this?

The antispam isnt working at all!

Html:

<form action="submit.php" class="col4" method="post">

    <p>Your name: <input name="name" type="text" size="100" />
    </p>

    <p>Your email: <input name="email" type="text" size="100" />    </p>
    <p><input name="website" type="text" class="website"/></p>
    <p class="antispam">Leave this empty: <input type="text" name="url" /> 
 </p>

    <p>Message: <textarea name="message" cols="100"></textarea>
    </p>

    <p><input type="submit" value="Send" /></p>

</form>

CSS:

form .website{ display:none; } /* hide because is spam protection */

PHP:

<?php

# spam protection
if (isset($_POST["website"]) && $_POST["website"] == "") {
    # your php code to mail here
} else {
    http_response_code(400);
    exit;
}


// if the url field is empty
if (isset($_POST['url']) && $_POST['url'] == '') {

    // put your email address here
    $youremail = 'admin@napleswebgraphics.com';

    // prepare a "pretty" version of the message
    $body = "This is the form that was just submitted<br />
    :
    Name:  $_POST[name]
    E-Mail: $_POST[email]
    Message: $_POST[message]";

    // Use the submitters email if they supplied one
    // (and it isn't trying to hack your form).
    // Otherwise send from your email address.

    if ($_POST['email'] && !preg_match("/[\r\n]/", $_POST['email'])) {
        $headers = "From: $_POST[email]";
    } else {
        $headers = "From: $youremail";
    }


    // finally, send the message
    mail($youremail, 'Contact Form', $body, $headers);
} // otherwise, let the spammer think that they got their message through ?>

<h1 align="center">Thank You!</h1>

<div align="center">I'll get back to you as soon as possible! Click <a
            href="index.html">here</a> to go back to the main page.
</div>

I want a specific answer to be the ONLY thing that allows the form to go through.

atymic
  • 3,093
  • 1
  • 13
  • 26

1 Answers1

1

Adding this check is very simple. In your form html, add a new field:

<p>Zebras are black and...: <input name="animal" type="text" /></p>

Then, in your PHP you can check for its existence and bail early if it's wrong. Add this to the top of your PHP file:

if (empty($_POST['animal']) || $_POST['url'] !== 'white') {
    http_response_code(400);
    die('wrong answer');
}
atymic
  • 3,093
  • 1
  • 13
  • 26