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 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题