联系表格反垃圾邮件JavaScript和/或PHP

时间:2015-08-19 21:18:19

标签: javascript php forms

我有一个我在Bootstrap响应式单页网站中使用的联系表单。表单工作正常,发送电子邮件就好了。我的网站没有获得大量的流量,我不喜欢Captcha字段,所以我想插入一个简单的字段供用户输入以确保它们是人类。我添加了一个简单的数学问题。现在,我需要知道如何验证用户在处理电子邮件之前输入了正确的数学答案。

我的表单使用contact_me.js文件和jqBootstrapBalidation.js文件来验证并将表单发送到contact_me.php来处理电子邮件。我尝试更新PHP(从这里有一些建议),但我无法让它工作。即使输入的数学答案不正确,也会始终发送电子邮件。

重要的是要注意我没有为此编写代码,我对js很新。表单和代码由startbootstrap.com模板提供。

我想强制用户输入数学问题的正确答案。我自己添加了这个字段。我将人员字段的变量添加到contact_me.js文件中(我假设我需要这样做)从表单中获取值。

再往下来.js文件然后使用ajax发布到contact_me.php来处理电子邮件。下面是它进一步验证字段并显示成功/错误消息的位置。在这里有什么地方我可以验证用户是否输入了正确的数学公式(答案应该是= 5)并且如果它是正确的,那么通过contact_me.php处理电子邮件并且如果答案不正确则显示错误消息没有发送到PHP并要求再试一次?下面是html,contact_me.js和contact_me.php。非常感谢你对此的帮助!

HTML:

 <form name="sentMessage" id="contactForm" novalidate>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Name</label>
                            <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Email Address</label>
                            <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Phone Number</label>
                            <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Message</label>
                            <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                    <div class="row control-group">
                        <div class="form-group col-xs-12 floating-label-form-group controls">
                            <label>Human</label>
                            <input type="text" class="form-control" placeholder="Two + 3 = ?" id="human" required data-validation-required-message="Please solve math equation to prove you are human">
                            <p class="help-block text-danger"></p>
                        </div>
                    </div>
                     <br>
                    <div id="success"></div>
                    <div class="row">
                        <div class="form-group col-xs-12">
                            <button type="submit" class="btn btn-success btn-lg">Send</button>
                        </div>
                    </div>
                  </form>

contact_me.js:

$(function() {

$("input,textarea").jqBootstrapValidation({
    preventSubmit: true,
    submitError: function($form, event, errors) {
        // additional error messages or events
    },
    submitSuccess: function($form, event) {
        // Prevent spam click and default submit behaviour
        $("#btnSubmit").attr("disabled", true);
        event.preventDefault();

        // get values from FORM
        var name = $("input#name").val();
        var email = $("input#email").val();
        var phone = $("input#phone").val();
        var message = $("textarea#message").val();
        var human = $("textarea#human").val();
        var firstName = name; // For Success/Failure Message
        // Check for white space in name for Success/Fail message
        if (firstName.indexOf(' ') >= 0) {
            firstName = name.split(' ').slice(0, -1).join(' ');
        }
        $.ajax({
            url: "././mail/contact_me.php",
            type: "POST",
            data: {
                name: name,
                phone: phone,
                email: email,
                message: message,
                human: human
            },
            cache: false,
            success: function() {
                // Enable button & show success message
                $("#btnSubmit").attr("disabled", false);
                $('#success').html("<div class='alert alert-success'>");
                $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-success')
                    .append("<strong>Your message has been sent. </strong>");
                $('#success > .alert-success')
                    .append('</div>');

                //clear all fields
                $('#contactForm').trigger("reset");
            },
            error: function() {
                // Fail message
                $('#success').html("<div class='alert alert-danger'>");
                $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                    .append("</button>");
                $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                $('#success > .alert-danger').append('</div>');
                //clear all fields
                $('#contactForm').trigger("reset");
            },
        })
    },
    filter: function() {
        return $(this).is(":visible");
    },
});

$("a[data-toggle=\"tab\"]").click(function(e) {
    e.preventDefault();
    $(this).tab("show");
});
});

// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
$('#success').html('');
});

contact_me.php:

<?php
// Check for empty fields
if(empty($_POST['name'])        ||
empty($_POST['email'])      ||
empty($_POST['phone'])      ||
empty($_POST['message'])    ||
empty($_POST['human'])  ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}

//Check if simple anti-bot test is correct
if ($human !== 5) {
   $errHuman = 'Your anti-spam is incorrect';
}   

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$message = $_POST['human'];

// Create the email and send the message
$to = 'info@mysite.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Portfolio Website Message:  $name";
$email_body = "You have received a new message from your portfolio website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@mysite.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address"; 
mail($to,$email_subject,$email_body,$headers);
return true;            
?>

1 个答案:

答案 0 :(得分:1)

这可能是由于contact_me.php中if语句后面的代码造成的。 它应该读

if($human !== 5) {
    $errMsg = "Anti-Spam is incorrect";
} else {
    // CUT ALL CODE FOLLOWING YOUR IF AND PASTE IN BETWEEN THIS ELSE.
}

当且仅当提交的答案为5时,才允许您发送电子邮件。

编辑 - JAVASCRIPT VALIDATION

你可以在if else语句中使用Ajax函数。

if(human === 5) {
/*
    PASTE AJAX FUNCTION
    CODE HERE, IT WILL RUN IF
    THEIR ANSWER IS CORRECT
*/
} else {
/*
    SEND ERROR FROM HERE
    IF THEIR ANSWER IS
    ANYTHING ELSE 
*/
}

将此代码插入Ajax代码当前启动的行

2ND编辑 -

if(human === 5) {
    $.ajax({
        url: "././mail/contact_me.php",
        type: "POST",
        data: {
            name: name,
            phone: phone,
            email: email,
            message: message,
            human: human
        },
        cache: false,
        success: function() {
            // Enable button & show success message
        $("#btnSubmit").attr("disabled", false);
            $('#success').html("<div class='alert alert-success'>");
            $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
            $('#success > .alert-success')
                .append("<strong>Your message has been sent. </strong>");
            $('#success > .alert-success')
                .append('</div>');

            //clear all fields
            $('#contactForm').trigger("reset");
        },
        error: function() {
            // Fail message
            $('#success').html("<div class='alert alert-danger'>");
            $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
            $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
            $('#success > .alert-danger').append('</div>');
            //clear all fields
            $('#contactForm').trigger("reset");
        },
    }); //inserted a semi-colon here to end the Ajax function
} else {
//The error from your Ajax code will not signify if the user's answer is incorrect but this else block will allow you to append an error like you said in the comments
} //end of if else block
// I BELIEVE THE CURLY BRACE AND COMMA FOLLOWING THIS ARE NOT NEEDED
},