简体   繁体   English

如何使用 AJAX 实现 reCAPTCHA 以在 php 中发送邮件?

[英]How to implement reCAPTCHA with AJAX for sending mail in php?

I'm trying to add Google's recaptcha in my website's contact form.我正在尝试在我网站的联系表单中添加 Google 的验证码。 I've used the <input type="submit"> instead of button tag for submitting the form.我使用<input type="submit">而不是按钮标签来提交表单。 But it doesn't work with AJAX.但它不适用于 AJAX。 And with button tag, the captcha response is always empty.使用按钮标签时,验证码响应始终为空。 You can check the problem on vipiny.com .您可以在vipiny.com上检查问题。

This is the contact form.这是联系表格。

<form action="" method="post" id="contactForm" name="contactForm">
    <div>
        <label for="contactName">Name <span class="required">*</span></label>
        <input type="text" value="" size="35" id="contactName" name="contactName">
    </div>
    <div>
        <label for="contactEmail">Email <span class="required">*</span></label>
        <input type="text" value="" size="35" id="contactEmail" name="contactEmail">
    </div>
    <div>
        <label for="contactSubject">Subject</label>
        <input type="text" value="" size="35" id="contactSubject" name="contactSubject">
    </div>
    <div>
        <label for="contactMessage">Message <span class="required">*</span></label>
        <textarea cols="50" rows="3" id="contactMessage" name="contactMessage"></textarea>
    </div>
    <div class="g-recaptcha captcha" data-theme="light" data-sitekey="6LfAkhQUAAAAAC2D3LxhB9XtYeoJGhuvR31sq9HW"></div>
    <div>
        <button class="submit">Submit</button>
    </div>
</form> <!-- Form End -->

And I'm using ajax to send the data to sendMail.php file.我正在使用 ajax 将数据发送到 sendMail.php 文件。

$('form#contactForm button.submit').click(function() {

  $('#image-loader').fadeIn();

  var contactName = $('#contactForm #contactName').val();
  var contactEmail = $('#contactForm #contactEmail').val();
  var contactSubject = $('#contactForm #contactSubject').val();
  var contactMessage = $('#contactForm #contactMessage').val();

  var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
           '&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage;

  $.ajax({

      type: "POST",
      url: "inc/sendEmail.php",
      data: data,
      success: function(msg) {

        // Message was sent
        if (msg == 'OK') {
           $('#image-loader').fadeOut();
           $('#message-warning').hide();
           $('#contactForm').fadeOut();
           $('#message-success').fadeIn();   
        }
        // There was an error
        else {
           $('#image-loader').fadeOut();
           $('#message-warning').html(msg);
            $('#message-warning').fadeIn();
        }

      }

  });
  return false;   }); });

And this is so far my sendMail.php file.到目前为止,这是我的 sendMail.php 文件。 I'm trying to validate that if $error['captcha'] is empty along with other input field checks, the mail will be sent.我试图验证如果$error['captcha']为空以及其他输入字段检查,邮件将被发送。

$secret = "<--secret key-->";
$user_ip = $_SERVER['REMOTE_ADDR'];

if(isset($_POST['g-recaptcha-response'])){
    $response = $_POST['g-recaptcha-response'];
    // echo "GOT response:".$response."<br/>";
}
else{
    // echo "No reCAPTCHA response.<br/>";
}

//Verify response data
$verifyResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$user_ip");
$responseData = json_decode($verifyResponse);
if(!$responseData->success){
    $error['captcha'] = "Please prove that you're not a robot.";    
}

Any suggestions what might be going wrong?有什么建议可能会出错吗?

You forgot to add the ?你忘了添加? after the url在网址之后

url: "inc/sendEmail.php?",

OR或者

you could leave out the ?你可以省略? and send your data like并发送您的数据,例如

data: { this: this, that: that, another: another},

also since you are not posting the g-recaptcha-response to the php file with the form, but instead with AJAX you have to send the post manually to your php file.此外,由于您没有使用表单将g-recaptcha-response到 php 文件,而是使用 AJAX,您必须手动将帖子发送到您的 php 文件。

var g-recaptcha-response= $('#contactForm .g-recaptcha-response').val();

var data = 'contactName=' + contactName + '&contactEmail=' + contactEmail +
       '&contactSubject=' + contactSubject + '&contactMessage=' + contactMessage + '&g-recaptcha-response=' + g-recaptcha-response;

you made also need this to confirm the recaptcha in php你也需要这个来确认php中的recaptcha

  require_once('recaptchalib.php');
  $privatekey = "your_private_key";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);

  if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
         "(reCAPTCHA said: " . $resp->error . ")");
  } else {
    // Your code here to handle a successful verification
  }

https://developers.google.com/recaptcha/old/docs/php https://developers.google.com/recaptcha/old/docs/php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM