2017-04-20 134 views
3

困惑,爲什麼這不起作用。提交表單時,我收到錯誤消息。沒有用file_get_contents驗證的Recaptcha

從我的形式:

<div class="g-recaptcha" data-sitekey="(site-key)"></div> 

PHP:

if(isset($_POST['g-recaptcha-response'])){ 
     $captcha=$_POST['g-recaptcha-response']; 
    } 

$secretKey = "(secret-key)"; 
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha); 
$responseKeys = json_decode($response,true); 
if(intval($responseKeys["success"]) === true) { 
    echo '<h3>Thanks for your message!</h3>'; 
} else { 
    echo '<h3>Error</h3>'; 
    } 

回答

9

的ReCaptcha文檔具體指定爲請求https://www.google.com/recaptcha/api/siteverify參數必須通過POST發送。你可以爲此使用CURL。

$ch = curl_init(); 

curl_setopt_array($ch, [ 
    CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify', 
    CURLOPT_POST => true, 
    CURLOPT_POSTFIELDS => [ 
     'secret' => $secretKey, 
     'response' => $captcha, 
     'remoteip' => $_SERVER['REMOTE_ADDR'] 
    ], 
    CURLOPT_RETURNTRANSFER => true 
]); 

$output = curl_exec($ch); 
curl_close($ch); 

$json = json_decode($output); 

// check response... 
+0

感謝您的回覆..我試圖實現這一點,並得到一個空白的屏幕。我應該如下檢查響應嗎? 'if(intval($ json [「success」])=== true){ echo'success'; } else { echo'error'; }' – Tom

+2

@Tom嘿!檢查它是這樣的:'if(isset($ json-> success)&& $ json-> success){echo'success'; }其他{回聲'錯誤'; }'這應該可行,但是如果你確實希望'$ json'是一個關聯數組,那麼在'json_decode'中添加第二個參數,其值爲true,這將返回一個關聯數組而不是對象:) – Yemiez

+0

我的heroooo!謝謝你,先生。 – Tom

3

請勿使用file_get_contents。 Google建議使用POST請求。 您可以使用的東西在線路下面

$curl = curl_init(); 
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1, 
    CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify', 
    CURLOPT_POST => 1, 
    CURLOPT_POSTFIELDS => array(
     'secret' => $secretKey, 
     'response' => $captcha 
    ) 
)); 
$response = curl_exec($curl); 
curl_close($curl); 

if(strpos($resp, '"success": true') !== FALSE) { 
    echo '<h3>Thanks for your message!</h3>'; 
} else { 
    echo "<h3>Error</h3>"; 
} 

編輯

Yemiez答案(只是讓我在拐角處)在處理響應部分,通過使用json_decode功能更好。