簡體   English   中英

如何使用AJAX-jQuery將Google reCAPTCHA v2響應代碼傳遞到服務器端PHP頁面

[英]How to pass Google reCAPTCHA v2 response code to server side PHP page using AJAX-jQuery

表單未使用AJAX-jQuery提交,因此未在服務器端PHP頁面上獲得響應密鑰。

表格頁

這部分非常簡單,如下所示。

<script src='https://www.google.com/recaptcha/api.js'></script>

<form name="frm_add" id="frm_add" novalidate>
    <div class="control-group form-group">
        <div class="controls input-group"> 
            <span class="input-group-addon"><i class="fa fa-user"></i></span>
            <input name="name" id="name" class="form-control" type="text" value="">
        </div>
        <p class="help-block"></p>
    </div> 

    <div class="g-recaptcha" data-sitekey="MY-SITE-KEY"></div>
    <div id="success"></div>

    <button type="submit" value="Submit">Submit</button> 
</form>

jQuery / AJAX頁面

如果刪除g-recaptcha-response: grecaptcha.getResponse(),此JS頁面中的代碼將使用jQuery-AJAX提交頁面,而不會出現任何問題,並且一切順利。 但是,當我將下面的示例代碼中編寫的代碼放在上面時,則表單沒有使用POST方法提交,因此我猜想這段代碼有問題。 我在互聯網上搜索並閱讀了許多教程和代碼,但無法解決此問題。

$(function() {
    $("#frm_add input,#frm_add textarea ,#frm_add select").jqBootstrapValidation( {
        .
        .
        $.ajax({
            url: "./user/offer_p.php",
            type: "POST",
            data: {
                g-recaptcha-response: grecaptcha.getResponse(),
                name: name
            },
            cache: false,
        .
        .
    }
}

服務器端PHP頁面

如果我直接使用POST方法(不使用jQuery-AJAX POST方法)提交表單,則以下代碼可以正常工作。

$ipaddress = $_SERVER['REMOTE_ADDR'];
$secretkey = "MY-SECRET-KEY";
$responsekey = $_POST['g-recaptcha-response'];
$url = "https://www.google.com/recaptcha/api/siteverify";

$post_data = http_build_query(
    array (
        'secret' => $secretkey,
        'response' => $responsekey,
        'remoteip' => $ipaddress
    )
);  

$options=array (
    'http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $post_data
    )
);

$context = stream_context_create($options);   
$result_json = file_get_contents($url, false, $context);
$resulting = json_decode($result_json, true);

if($resulting["success"] != 1)
{
    $response['status']='ERR';
    $response['message']= "Invalide Captcha!";
    echo json_encode($response); 
    return;
}

服務器端PHP頁面

  $response = file_get_contents ( "https://www.google.com/recaptcha/api/siteverify?secret=" . PRIVATE_CAPTCHA_KEY . "&response=" . $_POST ['g-recaptcha-response'] . "&remoteip=" . $_SERVER ['REMOTE_ADDR'] );
  $responseData = json_decode ( $response );

  if ($responseData->success) {
                 // TRUE
  }else{
               //False
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM