2016-10-06 59 views
1

我目前正試圖瞭解ReCaptcha如何工作。 我做了演示這個簡單的HTML表單:ReCaptcha檢查不起作用

<form id="comment_form" action="form.php" method="post"> 
    <input type="email"><br><br> 
    <textarea name="comment" rows="10"></textarea><br><br> 
    <input type="submit" name="submit" value="Post comment"><br><br> 
    <div class="g-recaptcha" data-sitekey="6LfXcggUAAAAAJ7txEVLU949P4SHWk5eXoSYksQ1"></div> 
</form> 
<script src='https://www.google.com/recaptcha/api.js'></script> 

,這是我的PHP代碼:

$email; 
$comment; 
$captcha; 
if(isset($_POST['email'])) 
{ 
    $email=$_POST['email']; 
} 
if(isset($_POST['comment'])) 
{ 
    $email=$_POST['comment']; 
} 
if(isset($_POST['g-recaptcha-response'])) 
{ 
    $captcha=$_POST['g-recaptcha-response']; 
} 
if(empty($captcha)) 
{ 
    echo '<h2>Please check the the captcha form.</h2>'; 
    exit; 
} 
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=DONTPUBLUSHYOURSECRETDUDE&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); 
if($response->success === false) 
{ 
    die('<h2>You are a spammer</h2>'); 
} 
echo '<h2>Thanks for posting your comment.</h2>'; 

此腳本輸出甚至儘管用戶沒有通過驗證碼的挑戰Thanks for posting your comment

+0

@timyRS能否請你給我一個例子,如何用JavaScript來實現。我發現可以使用「g-recaptcha-response」,但我沒有理解它在這個內容上的作品。 –

+0

你已經發布了你的密鑰,建議你改變它。 – timmyRS

+0

是的,這只是爲了演示的目的。謝謝你的答案,我明天將在學校嘗試。 –

回答

0

嘗試以下操作:

$email;$comment;$captcha; 
    if(isset($_POST['email'])){ 
     $email=$_POST['email']; 
    }if(isset($_POST['comment'])){ 
     $email=$_POST['comment']; 
    }if(isset($_POST['g-recaptcha-response'])){ 
     $captcha=$_POST['g-recaptcha-response']; 
    } 
    if(!$captcha){ 
     echo '<h2>Please check the the captcha form.</h2>'; 
     exit; 
    } 
    $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LfXcggUAAAAAP887f6E0W4fZF6mnp1C1lBpAUwv&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']); 
    $responseKeys = json_decode($response, true); 
    if($responseKeys["success"] !== 1) 
    { 
     echo '<h2>You are spammer !</h2>'; 
    }else 
    { 
     echo '<h2>Thanks for posting comment.</h2>'; 
    } 
0

你忘了json_decode響應。

我修復了你的代碼。

<?php 
if(empty($_POST["email"]) 
|| empty($_POST["comment"]) 
|| empty($_POST["g-recaptcha-response"])) 
{ 
    die("Please fill out everything."); 
} 
$email = $_POST["email"]; 
$comment = $_POST["comment"]; 
$captcha = $_POST["g-recaptcha-response"]; 
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=XXX&response=".$captcha), true); 
if($response["success"] !== true) 
{ 
    die("You did not pass the captcha"); 
} 
echo "You passed the captcha. :D";