我目前正在尝试了解ReCaptcha的工作原理。 为了演示目的,我制作了这个简单的html表单:
<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>';
即使用户未通过ReCaptcha的挑战,此脚本也会输出Thanks for posting your comment
。
答案 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>';
}
答案 1 :(得分: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";