【问题标题】:Contact Form anti-spam JavaScript and/or PHP联系表格反垃圾邮件 JavaScript 和/或 PHP
【发布时间】:2015-08-19 21:18:18
【问题描述】:

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

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

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

我想强制用户输入数学问题的正确答案。我自己添加了这个字段。我将human 字段的变量添加到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;            
?>

【问题讨论】:

  • 写的很长,我想你可以把if ($human !== 5) {变成if ($_POST['human'] !== 5) {die('Your anti-spam is incorrect');}
  • $human 定义在哪里?
  • 感谢@chris85 的建议。我尝试了您的编辑,但电子邮件仍然通过不正确的反垃圾邮件。我仍然认为问题在于contact_me.js。由于所有其他验证都在此处进行,因此必须有一种方法来验证此处的反垃圾邮件,如果不正确,甚至不将电子邮件发送到 contact_me.php。如果反垃圾邮件不正确,它还应该显示错误消息。如果任何必填字段留空或电子邮件格式不正确,则会显示来自 contact_me.js 的错误。我们可以对反垃圾邮件领域做同样的事情吗?

标签: javascript php forms


【解决方案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 验证

您将在 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 代码当前开始的行中

第二次编辑 -

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
},

【讨论】:

  • 谢谢@SidTheBeard。我尝试了您的编辑,但电子邮件仍然发送错误的反垃圾邮件答案。您知道我如何编辑contact_me.js 以使其在发送到contact_me.php 进行处理之前验证反垃圾邮件字段 - 类似于它对其他表单字段所做的事情?现在,如果必填字段为空或使用了错误的格式,它会发布一条错误消息并且不会发送到contact_me.php。如果输入了错误的反垃圾邮件答案并且不发送到contact_me.php,我希望显示一条错误消息。感谢您对此的帮助。
  • @Rex 没问题。如果您想在 JavaScript 中进行验证,请将您的 Ajax 函数包装在 if/else 块中。在这种情况下,“if”将测试“human”是否 === 5。如果这是真的,那么发送 Ajax 语句。如果不显示错误。就像您在 Ajax 调用的错误部分所做的那样。
  • 感谢您的反馈。我还在学习 JavaScript。这里使用的 js 代码不是我写的,它是 startbootstrap.com 中包含的模板。你能分享一个我应该如何写的简单例子吗?如果可行,我会想办法给你买啤酒!!!
  • @Rex 我刚刚发布了 if/else 代码,只需按照几个步骤所说的做,它应该可以正常工作。
  • @Rex 希望编辑对您有所帮助。如果是,请接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-05
相关资源
最近更新 更多