新的谷歌recaptchacheckbox服务器端PHP

我刚刚设置了新的谷歌recaptcha与checkbox,它在网站上工作正常,但是我不知道如何在服务器端使用PHP做到这一点,我试图使用下面的旧代码,但即使不使用recaptcha。

require_once('recaptchalib.php'); $privatekey = "my key"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { $errCapt='<p style="color:#D6012C ">The CAPTCHA Code wasnot entered correctly.</p>';} 

这是解决scheme

的index.html

 <html> <head> <title>Google recapcha demo - Codeforgeek</title> <script src='https://www.google.com/recaptcha/api.js'></script> </head> <body> <h1>Google reCAPTHA Demo</h1> <form id="comment_form" action="form.php" method="post"> <input type="email" placeholder="Type your email" size="40"><br><br> <textarea name="comment" rows="8" cols="39"></textarea><br><br> <input type="submit" name="submit" value="Post comment"><br><br> <div class="g-recaptcha" data-sitekey="=== Your site key ==="></div> </form> </body> </html> 

verify.php

 <?php $email;$comment;$captcha; if(isset($_POST['email'])) $email=$_POST['email']; if(isset($_POST['comment'])) $comment=$_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=json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true); if($response['success'] == false) { echo '<h2>You are spammer ! Get the @$%K out</h2>'; } else { echo '<h2>Thanks for posting comment.</h2>'; } ?> 

http://codeforgeek.com/2014/12/google-recaptcha-tutorial/

私钥安全

虽然这里的答案肯定是有效的,但他们正在使用一个GET请求,这个请求公开了你的私钥(即使使用了https )。 在Google Developers上 ,指定的方法是POST

通过POSTvalidation

 function isValid() { try { $url = 'https://www.google.com/recaptcha/api/siteverify'; $data = ['secret' => '[YOUR SECRET KEY]', 'response' => $_POST['g-recaptcha-response'], 'remoteip' => $_SERVER['REMOTE_ADDR']]; $options = [ 'http' => [ 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data) ] ]; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); return json_decode($result)->success; } catch (Exception $e) { return null; } } 

数组语法:我使用“新”数组语法( []而不是array(..) )。 如果你的PHP版本不支持这个,你将不得不相应地编辑这3个数组定义(见注释)。

返回值:如果用户有效,则此函数返回true否则返回false如果发生错误,则返回null 。 你可以使用它,例如简单地通过编写if (isValid()) { ... }

我不是这些解决scheme的粉丝。 我用这个来代替:

 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, [ 'secret' => $privatekey, 'response' => $_POST['g-recaptcha-response'], 'remoteip' => $_SERVER['REMOTE_ADDR'] ]); $resp = json_decode(curl_exec($ch)); curl_close($ch); if ($resp->success) { // Success } else { // failure } 

我认为,这是优越的,因为你确保它被发送到服务器,并没有做一个尴尬的'file_get_contents'调用。 这与此处介绍的recaptcha 2.0兼容: https : //developers.google.com/recaptcha/docs/verify

我觉得这个更清洁。 我看到大多数解决scheme是file_get_contents,当我觉得curl就足够了。

简单和最好的解决scheme如下。
的index.html

 <form action="submit.php" method="POST"> <input type="text" name="name" value="" /> <input type="text" name="email" value="" /> <textarea type="text" name="message"></textarea> <div class="g-recaptcha" data-sitekey="Insert Your Site Key"></div> <input type="submit" name="submit" value="SUBMIT"> </form> 

submit.php

 <?php if(isset($_POST['submit']) && !empty($_POST['submit'])){ if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){ //your site secret key $secret = 'InsertSiteSecretKey'; //get verify response data $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']); $responseData = json_decode($verifyResponse); if($responseData->success){ //contact form submission code goes here $succMsg = 'Your contact request have submitted successfully.'; }else{ $errMsg = 'Robot verification failed, please try again.'; } }else{ $errMsg = 'Please click on the reCAPTCHA box.'; } } ?> 

我从这里find了这个参考和完整的教程 – 使用PHP的新的Google reCAPTCHA

我喜欢莱维特的答案,并最终使用它。 但我只想指出,以防万一,有新的reCAPTCHA官方的Google PHP库: https : //github.com/google/recaptcha

最新版本(现在是1.1.2)支持Composer,并包含一个示例,您可以运行该示例查看是否已正确configuration所有内容。

下面你可以看到这个官方库附带的例子的一部分(为了清晰起见,我做了小的修改):

 // Make the call to verify the response and also pass the user's IP address $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']); if ($resp->isSuccess()) { // If the response is a success, that's it! ?> <h2>Success!</h2> <p>That's it. Everything is working. Go integrate this into your real project.</p> <p><a href="/">Try again</a></p> <?php } else { // If it's not successful, then one or more error codes will be returned. ?> <h2>Something went wrong</h2> <p>The following error was returned: <?php foreach ($resp->getErrorCodes() as $code) { echo '<tt>' , $code , '</tt> '; } ?></p> <p>Check the error code reference at <tt><a href="https://developers.google.com/recaptcha/docs/verify#error-code-reference">https://developers.google.com/recaptcha/docs/verify#error-code-reference</a></tt>. <p><strong>Note:</strong> Error code <tt>missing-input-response</tt> may mean the user just didn't complete the reCAPTCHA.</p> <p><a href="/">Try again</a></p> <?php } 

希望它可以帮助别人。

在上面的例子中。 对于我来说,这个if($response.success==false)不起作用。 这里是正确的PHP代码:

 $url = 'https://www.google.com/recaptcha/api/siteverify'; $privatekey = "--your_key--"; $response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']); $data = json_decode($response); if (isset($data->success) AND $data->success==true) { // everything is ok! } else { // spam } 

在服务器端使用PHP进行validation。 两件最重要的事情你需要考虑。

 1. $_POST['g-recaptcha-response'] 2.$secretKey = '6LeycSQTAAAAAMM3AeG62pBslQZwBTwCbzeKt06V'; $verifydata = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']); $response= json_decode($verifydata); 

如果你得到$ verifydata true你完成了
为更多检查这
Google reCaptcha使用PHP | 只有两步整合

它与mattgen88类似,但我只是修复了CURLOPT_HEADER,并重新定义了它在domain.com主机服务器上工作的数组。 这一个不能在我的xampp本地主机上工作。 那些小小的错误却花了很长时间才弄清楚。 这个代码在domain.com托pipe上进行了testing。

  $privatekey = 'your google captcha private key'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify"); curl_setopt($ch, CURLOPT_HEADER, 'Content-Type: application/json'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array( 'secret' => $privatekey, 'response' => $_POST['g-recaptcha-response'], 'remoteip' => $_SERVER['REMOTE_ADDR'] ) ); $resp = json_decode(curl_exec($ch)); curl_close($ch); if ($resp->success) { // Success echo 'captcha'; } else { // failure echo 'no captcha'; } 

这里有一个简单的例子。 只记得提供谷歌API的secretKey和siteKey。

 <?php $siteKey = 'Provide element from google'; $secretKey = 'Provide element from google'; if($_POST['submit']){ $username = $_POST['username']; $responseKey = $_POST['g-recaptcha-response']; $userIP = $_SERVER['REMOTE_ADDR']; $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP"; $response = file_get_contents($url); $response = json_decode($response); if($response->success){ echo "Verification is correct. Your name is $username"; } else { echo "Verification failed"; } } ?> <html> <meta> <title>Google ReCaptcha</title> </meta> <body> <form action="index.php" method="post"> <input type="text" name="username" placeholder="Write your name"/> <div class="g-recaptcha" data-sitekey="<?= $siteKey ?>"></div> <input type="submit" name="submit" value="send"/> </form> <script src='https://www.google.com/recaptcha/api.js'></script> </body>