我是一个PHP noob,我正在尝试将新的google recatcha合并到一个网站中。html文档中有一个表单,它调用一个"sendemail.php"文件(下面的代码)。问题是,无论用户是否正确地进行了重述,表单都在工作。在我的代码中,它将始终执行"codeB",而不管用户是否未能完成重述。
我搞砸了什么?
<?php
$captcha=$_POST['g-recaptcha-response'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=##########11&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
//codeA that I want to execute if the recaptcha fails
echo '<p>Please Go Back And Try Again</p>';
}
else
{
//codeB that I want to execute upon success of the recaptcha
}
?>
您的代码有两个错误,第一个是上面有人提到您需要使用json_decode。其次,您不能通过在$response前面添加.success来检查值。
这是正确的代码,它的工作:
$captchaSecretCode = 'placeYourSecretCodeHere';
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$captchaSecretCode."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if($response['success'] == true)
{
echo 'true';
}else{
echo 'false';
}
也许需要检查的一件事是,在php.ini中是否打开了fopen值。在将repatcha合并到这个特定的站点中时,我遇到了各种各样的问题。它在其他人身上效果很好,我不明白为什么。然后我看到在这个网站的另一篇帖子中提到了"fopen",然后低看,设置被取消了。
查找:
allow_url_fopen
allow_url_include
我把它们都从"关闭"改为"打开",然后代码就工作了!
这是一个教程:-
$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=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo '<h2>You are spammer ! Get the @$%K out</h2>';
}else
{
echo '<h2>Thanks for posting comment.</h2>';
}
希望这能有所帮助。。
在Plesk上的PHP.INI文件中,有两行代码可以启用这些设置
;;;;;;;;;;;;;;;;;;
; Fopen wrappers ;
;;;;;;;;;;;;;;;;;;
; Whether to allow the treatment of URLs (like http:// or ftp://) as files.
; http://php.net/allow-url-fopen
allow_url_fopen = On
; Whether to allow include/require to open URLs (like http:// or ftp://) as files.
; http://php.net/allow-url-include
allow_url_include = On
您需要使用函数json_encode:
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
$response = json_encode($response);
if($response->success==false){
echo 'spamer';
}
else{
echo 'ok';
}