douci1918 2015-08-22 07:19
浏览 57
已采纳

验证JS中的secureimage验证码

After many different attempts I was finally able to add a working captcha to my bootstrap contact form. I ended up using SecureImage from phpcaptcha.org. It seems to be working fine - it sends the email if the captcha is entered correctly and it does NOT send the email if the captcha is entered incorrectly. However, I cannot get it to display an error message if the incorrect captcha is entered. Instead, it still displays a message saying the email was sent successfully, when in reality it is not. My contact form uses a contact_me.js file with an ajax function to validate and send the form content to a contact_me.php file for processing. The form is validated using jqBoostrapValidation.js in combination with the contact_me.js.

How can I get it to post an error message on the html page (as it does with the other field validations) if the incorrect captcha is entered. I am new to PHP and JS/Ajax and the contact form I am using is a template supplied by startBootstrap.com. I assume I need some kind of callback function to bring the captcha failure result from the PHP back to the contact_me.js file to display the error - but I don't know how to do this. Any help would be greatly appreciated.

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>
                    <br>        
                    <img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
                    <input type="text" name="captcha_code" size="10" id="captcha_code" maxlength="6" />

[ Different Image ]

Send

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 captcha_code = $("input#captcha_code").val();
            var message = $("textarea#message").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,
                    captcha_code: captcha_code,
                    message: message
                },
                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
session_start();
// Check for empty fields
if(empty($_POST['name'])        ||
empty($_POST['email'])      ||
empty($_POST['phone'])      ||
empty($_POST['message'])    ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}

include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();

if ($securimage->check($_POST['captcha_code']) == false) {
  // the code was incorrect
  echo "The security code entered was incorrect.<br /><br />";
  echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
  exit;
}


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

// Create the email and send the message
$to = 'info@rexmillerportfolio.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.

"."Here are the details:

Name: $name

Email: $email_address

Phone: $phone

Message:
$message";
$headers = "From: noreply@rexmillerportfolio.com
"; // 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条回答 默认 最新

  • dtnqbre7980007 2015-08-24 20:06
    关注

    The reason it looks like a success on the form side is because jQuery's ajax success method gets called regardless of the value of the captcha or errors in the contact form. This only means the server returned a successful response.

    You will need to modify the PHP and Javascript code a bit to handle form errors.

    Here is a suggestion for changing the PHP code to return a JSON response that you can then check on the client side:

    <?php
    session_start();
    $response = array('error' => true, 'message' => 'OK');
    
    // Check for empty fields
    if(empty($_POST['name'])        ||
    empty($_POST['email'])      ||
    empty($_POST['phone'])      ||
    empty($_POST['message'])    ||
    !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
    {
        $response['message'] = "No arguments Provided!";
        die(json_encode($response));
    }
    
    include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
    $securimage = new Securimage();
    
    if ($securimage->check($_POST['captcha_code']) == false) {
      // the code was incorrect
        $response['message'] = "The security code entered was incorrect.";
        die(json_encode($response));
    }
    
    
    $name = $_POST['name'];
    $email_address = $_POST['email'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    
    // Create the email and send the message
    $to = 'info@rexmillerportfolio.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.
    
    "."Here are the details:
    
    Name: $name
    
    Email: $email_address
    
    Phone: $phone
    
    Message:
    $message";
    $headers = "From: noreply@rexmillerportfolio.com
    "; // 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);
    
    $response['error'] = false;
    
    die(json_encode($response));
    

    Then modify the Javascript like this to look at the JSON response:

    $(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 captcha_code = $("input#captcha_code").val();
                var message = $("textarea#message").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",
                    dataType: 'json',
                    data: {
                        name: name,
                        phone: phone,
                        email: email,
                        captcha_code: captcha_code,
                        message: message
                    },
                    cache: false,
                    success: function(response) {
                        if (response.error) {
                            alert(response.message);
                            // TODO: customize to use dialog to show error
                        } else {
                // 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('');
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)