验证NoCaptcha ReCaptcha

时间:2016-11-17 03:14:00

标签: javascript php validation recaptcha

我已经浏览了整个互联网,并在这里搜索了问题,并且找不到重新验证的解决方案。我使用3个文件作为我的表单,Html文件,JS文件进行验证(bootstrapValidator)和php文件发送邮件,这是用phpmailer。表单可以在发送邮件时将邮件发送出去并清除表单。我确实在表单中插入了验证码。 我想弄清楚的是如何正确地重新使用表格。现在,当我点击发送并且没有填写的字段显示错误,而不是验证码。正确填写字段后,将删除错误。点击发送,它会将信息发送到地址。只是没有能够重新使用表格,所以当点击发送和验证码没有被检查时,表格不会被发送。

这只是我尝试验证的方法之一,将其放在我的php表单上,位于date_default_timezone_set上方的右上方(' Etc / UTC');没有运气

if(isset($_POST['submit']) && !empty($_POST['submit'])):
     if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])):
        //your site secret key
        $secret = 'your secret key';
        //get verify response data
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        $responseData = json_decode($verifyResponse);
        if($responseData->success):

这是HTML文件:

<form class="form-horizontal" action="" method="post" id="contact_form">

    设置预约

 <div class="col-md-12">
   <div class="allFields">* ALL FIELDS REQUIRED *</div>
 </div>

 <div id="mainContent" class="col-sm-12">

  <!-- Full Name -->

    <div class="form-group">
     <label for="fullname" class="col-md-4 control-label">Full Name*</label>
     <div class="col-md-5 inputGroupContainer">
      <div class="input-group">
       <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
       <input type="text" placeholder="Full Name" name="fullname" class="form-control">
      </div>
     </div>
    </div> 

   <!-- Address -->  

    <div class="form-group"> 
     <label for="address" class="col-md-4 control-label">Address</label>
     <div class="col-md-5 inputGroupContainer">
      <div class="input-group">
       <span class="input-group-addon"><i class="glyphicon glyphicon-road"></i></span>
       <input type="text" placeholder="Address" name="address" class="form-control">
      </div>
     </div>
    </div>

   <!-- City -->

    <div class="form-group"> 
     <label for="city" class="col-md-4 control-label">City</label>
     <div class="col-md-5 inputGroupContainer">
      <div class="input-group">
       <span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
       <input type="text" placeholder="City" name="city" class="form-control">
      </div>
     </div> 
    </div>

   <!-- State -->

    <div class="form-group"> 
     <label class="col-md-4 control-label">State</label>
     <div class="col-md-5 selectContainer">
      <div class="input-group">
       <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span>
        <select name="state" class="form-control selectpicker" >
         <option value=" " >Please select your state</option>
         <option>Ohio</option>
         <option>Pennsylvania</option>
        </select>
      </div>
     </div>
    </div> 

   <!-- Zip Code -->

    <div class="form-group"> 
     <label for="zipcode" class="col-md-4 control-label">Zip Code</label>
     <div class="col-md-5 inputGroupContainer">
      <div class="input-group">
       <span class="input-group-addon"><i class="glyphicon glyphicon-globe"></i></span>
       <input type="text" placeholder="Zip Code" name="zipcode" class="form-control">
      </div>
     </div>
    </div>

   <!-- Phone -->

    <div class="form-group">
     <label for="phone" class="col-md-4 control-label">Phone #</label>
     <div class="col-md-5 inputGroupContainer">
      <div class="input-group">
       <span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
       <input type="text" placeholder="(330)222-2222" name="phone" class="form-control">
      </div>
     </div>
    </div>

   <!-- Email -->

    <div class="form-group"> 
     <label for="email" class="col-md-4 control-label">E-mail</label>
     <div class="col-md-5 inputGroupContainer">
      <div class="input-group">
       <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
       <input type="text" placeholder="E-mail Address" name="email" class="form-control">
      </div>
     </div>
    </div>

   <!-- Appointment Reason -->

    <div class="form-group"> 
     <label class="col-md-4 control-label">Appt Reason</label>
     <div class="col-md-5 selectContainer">
      <div class="input-group">
       <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span>
        <select name="reason" class="form-control selectpicker" >
         <option value=" ">Select Your Appointment Reason</option>
         <option>Roofing</option>
         <option>Siding</option>
         <option>Doors</option>
         <option>Windows</option>
         <option>Decking</option>
         <option>Comfort Rooms</option>
         <option>Kitchen</option>
        </select>
      </div>
     </div>
    </div>

   <!-- Appointment Date -->

    <div class="form-group">
     <label class="col-md-4 control-label">Appt. Date</label>
     <div class="col-md-5 inputGroupContainer">
      <div class="input-group date" id="datepicker">
       <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
       <input type="text" placeholder="Date you would like Appointment" name="apptDate" class="form-control">
      </div>
     </div>
    </div> 

   <!-- Appointment Time -->

    <div class="form-group">
     <label class="col-md-4 control-label">Appt. Time</label>
     <div class="col-md-5 inputGroupContainer">
      <div class="input-group date" id="timepicker">
       <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
       <input type="text" placeholder="Time you would like Appointment" name="apptTime" class="form-control">
      </div>
     </div> 
    </div>

   <!-- Contact Method -->

    <div class="form-group"> 
     <label class="col-md-4 control-label">Contact You</label>
     <div class="col-md-5 selectContainer">
      <div class="input-group">
       <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span>
        <select name="method" class="form-control selectpicker" >
        <option value=" ">Select Your Contact Method</option>
        <option>Email</option>
        <option>Phone</option>
       </select>
      </div>
     </div>
    </div> 

   <!-- Project Description -->

    <div class="form-group"> 
     <label for="comments" class="col-md-4 control-label">Project Description</label>
     <div class="col-md-5 inputGroupContainer">
      <div class="input-group">
       <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
       <textarea name="comments" placeholder="Project Description" rows="5" class="form-control"></textarea>
      </div>
     </div>
    </div> 


     <div class="form-group">
      <label class="col-md-4 control-label">Captcha</label>
      <div class="col-md-5 inputGroupContainer">
       <div class="g-recaptcha" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXX"></div>
     </div>
    </div>

    <div class="form-group">
     <div class="col-md-offset-4 col-md-5" id="captchaMessage"></div>
    </div>

    <!-- Submit Button -->

    <div class="form-group">
     <div class="col-md-offset-4 col-md-5">
     <button type="submit" name="submit" class="btn btn-primary">Send <span class="glyphicon glyphicon-send"></span></button>
     </div>
    </div>



 </div> <!-- mainContent -->

</fieldset>
</form>

JS文件:

 $(document).ready(function() {
$('#contact_form').bootstrapValidator({

    // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    submitHandler: function(validator, form, submitButton) {

            $.ajax({
              type: "POST",
              url: "appt.php",
              data: $('#contact_form').serialize(),
              success: function(){
                $('#contact_form').each(function(){
                      this.reset();
               $(contact_form).data('bootstrapValidator').resetForm();
                });
             },
              error: function(){
                alert("error");
              }
            });//close ajax
    },
    fields: {
        fullname: {
            validators: {
                    stringLength: {
                    min: 2,
                },
                    notEmpty: {
                    message: 'Please supply your full name'
                }
            }
        },
         address: {
            validators: {
                 stringLength: {
                    min: 8,
                },
                notEmpty: {
                    message: 'Please supply your street address'
                }
            }
        },
        city: {
            validators: {
                 stringLength: {
                    min: 4,
                },
                notEmpty: {
                    message: 'Please supply your city'
                }
            }
        },
        state: {
            validators: {
                notEmpty: {
                    message: 'Please select your state'
                }
            }
        },
        zipcode: {
            validators: {
                stringLength: {
                    min: 5,
                },
                notEmpty: {
                    message: 'Please supply your zip code'
                },
                zipCode: {
                    country: 'US',
                    message: 'Please supply a vaild zip code'
                }
            }
        },
         phone: {
            validators: {
                notEmpty: {
                    message: 'Please supply your phone number'
                },
                phone: {
                    country: 'US',
                    message: 'Please supply a vaild phone number with area code'
                }
            }
        },
         email: {
            validators: {
                notEmpty: {
                    message: 'Please supply your email address'
                },
                emailAddress: {
                    message: 'Please supply a valid email address'
                }
            }
        },
        reason: {
            validators: {
                notEmpty: {
                    message: 'Please select what your appointment is for'
                }
            }
        },
        method: {
            validators: {
                notEmpty: {
                    message: 'Please select your preferred contact method'
                }
            }
        },
        comments: {
            validators: {
                  stringLength: {
                    min: 10,
                    max: 200,
                    message:'Please enter at least 10 characters and no more than 200'
                },
                notEmpty: {
                    message: 'Please supply a description of your project'
                }
                }
            },

        }
    })
 });

要发送的PHP文件:

<?php
/**
 * This example shows settings to use when sending via Google's Gmail servers.
 */

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
date_default_timezone_set('Etc/UTC');   

//Contact Form Data
$fullnameField = $_POST['fullname'];
$addressField = $_POST['address'];
$cityField = $_POST['city'];
$stateField = $_POST['state'];
$zipcodeField = $_POST['zipcode'];
$phoneField = $_POST['phone'];
$emailField = $_POST['email'];
$apptReasonField = $_POST['reason'];
$apptDateField = $_POST['apptDate'];
$apptTimeField = $_POST['apptTime'];
$methodField = $_POST['method'];
$commentsField = $_POST['comments'];

require 'mailer/PHPMailerAutoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer();

//Tell PHPMailer to use SMTP
$mail->isSMTP();

//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;

//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';

//Set the hostname of the mail server
$mail->Host = 'smtp.aol.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 587;

//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "xxxxxx";

//Password to use for SMTP authentication
$mail->Password = "xxxxxxxx";

//Set who the message is to be sent from
$mail->setFrom('xxxxxxxx');

//Set who the message is to be sent to
$mail->addAddress('xxxxxxxxxx');

//Set the subject line
$mail->Subject = 'Information For Appointment Wanted';

//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->Body = <<<EOD
<br><p>Here is the information $fullnameField entered in your Appointment form.</p>
<br><hr><br>
<b>Name:</b>&nbsp; $fullnameField<hr><br>
<b>Address:</b>&nbsp; $addressField<hr><br>
<b>City:</b>&nbsp; $cityField<hr><br>
<b>State:</b>&nbsp; $stateField<hr><br>
<b>Zip Code:</b>&nbsp; $zipcodeField<hr><br>
<b>Phone #:</b>&nbsp; $phoneField<hr><br>
<b>E-mail:</b>&nbsp; $emailField<hr><br>
<b>Appointment Reason:</b>&nbsp; $apptReasonField<hr><br>
<b>Date Wanted For Appointment:</b>&nbsp; $apptDateField<hr><br>
<b>Time Wanted For Appointment:</b>&nbsp; $apptTimeField<hr><br>
<b>Best Way To Contact You:</b>&nbsp; $methodField<hr><br>
<b>Project Description:</b>&nbsp; $commentsField<hr><br>
EOD;


//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';

//send the message, check for errors
if(!$mail->Send())
{
   echo "Mailer Error: " . $mail->ErrorInfo;
}else{
    echo "Message has been sent";
}

?>

1 个答案:

答案 0 :(得分:0)

您实际上是在尝试扩展客户端验证以包含您的reCaptcha。由于reCaptcha不是输入,我不相信你可以很容易地扩展你的Bootstrap验证器。但是,您可以添加一些额外的javascript来添加此验证。

  • 您需要一些javascript变量来跟踪您的reCaptcha是否已经解决:

    var captcha_passed = false;
    
  • 告诉Google的reCaptcha成功完成后调用您的函数:

    <div class="g-recaptcha" data-callback="on_captcha_filled" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXX"></div>
    
  • 添加另一个标签,让您的用户知道错过了。把它隐藏起来。如果他们在没有reCaptcha的情况下提交,javascript将取消隐藏。

    <div class="form-group">
        <label class="col-md-4 control-label">Captcha</label>
        <div class="col-md-5 inputGroupContainer">
        <div class="g-recaptcha" data-callback="on_captcha_filled" data-sitekey="XXXXXXXXXXXXXXXXXXXXXXXXX"></div>
        <label id="lblCaptchaRequired" hidden>Please complete the reCaptcha</label>
    </div>
    
  • 添加要由reCaptcha调用的javascript函数:

    /*
    *   Google reCaptcha data-callback handler.
    *   Sets captcha_passed to true to allow form submission and hides captcha required label.
    */
    function on_captcha_filled() {
        captch_passed = true;
        $('#lblCaptchaRequired').hidden = true;
    }
    
  • 在您的提交处理程序中添加一项检查,以验证reCaptcha是否已通过:

    submitHandler: function(validator, form, submitButton) {
        if (captcha_passed) {
            $.ajax({
                type: "POST",
                url: "appt.php",
                data: $('#contact_form').serialize(),
                success: function(){
                    $('#contact_form').each(function(){
                        this.reset();
                        $(contact_form).data('bootstrapValidator').resetForm();
                    });
                },
                error: function(){
                    alert("error");
                }
            });//close ajax
        }
        else {
            $('#lblCaptchaRequired').hidden = false;
        }
    },
    

现在,当您的用户尝试提交而未先完成reCaptcha时,他们会收到通知,表单将不会提交。