php 如何在服务器端验证 Google reCAPTCHA v3?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27274157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate Google reCAPTCHA v3 on server side?
提问by Moatez
I've just set up the new google recaptcha with checkbox, it's working fine on front end, however I don't know how to handle it on server side using PHP. I've tried to use the old code below but the form is sent even if the captcha is not valid.
我刚刚使用复选框设置了新的 google recaptcha,它在前端工作正常,但是我不知道如何使用 PHP 在服务器端处理它。我尝试使用下面的旧代码,但即使验证码无效,也会发送表单。
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>';}
回答by Levite
Private key safety
私钥安全
While the answers here are definately working, they are using a GET
request, which exposes your private key (even though https
is used). On Google Developersthe specified method is POST
.
虽然这里的答案肯定有效,但他们正在使用一个GET
请求,该请求会公开您的私钥(即使https
已使用)。在Google Developers 上,指定的方法是POST
。
For a little bit more detail: https://stackoverflow.com/a/323286/1680919
更多细节:https: //stackoverflow.com/a/323286/1680919
Verification via POST
通过 POST 验证
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 Syntax:I use the "new" array syntax ( [
and ]
instead of array(..)
). If your php version does not support this yet, you will have to edit those 3 array definitions accordingly (see comment).
数组语法:我使用“新”数组语法([
而]
不是array(..)
)。如果您的 php 版本尚不支持此功能,则您必须相应地编辑这 3 个数组定义(请参阅注释)。
Return Values:This function returns true
if the user is valid, false
if not, and null
if an error occured. You can use it for example simply by writing if (isValid()) { ... }
返回值:此函数返回true
用户是否有效,false
如果无效,以及null
是否发生错误。例如,您可以通过编写简单地使用它if (isValid()) { ... }
回答by CDZ
this is solution
这是解决方案
index.html
索引.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
<?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>';
}
?>
回答by mattgen88
I'm not a fan of any of these solutions. I use this instead:
我不喜欢这些解决方案中的任何一个。我用这个代替:
$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
}
I'd argue that this is superior because you ensure it is being POSTed to the server and it's not making an awkward 'file_get_contents' call. This is compatible with recaptcha 2.0 described here: https://developers.google.com/recaptcha/docs/verify
我认为这是优越的,因为您确保它被发布到服务器并且它不会进行尴尬的“file_get_contents”调用。这与此处描述的 recaptcha 2.0 兼容:https: //developers.google.com/recaptcha/docs/verify
I find this cleaner. I see most solutions are file_get_contents, when I feel curl would suffice.
我觉得这个更干净。我看到大多数解决方案都是 file_get_contents,当我觉得 curl 就足够了。
回答by JoyGuru
Easy and best solution is the following.
index.html
简单和最好的解决方案如下。
索引.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
<?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.';
}
}
?>
I have found this reference and full tutorial from here - Using new Google reCAPTCHA with PHP
我从这里找到了这个参考和完整教程 - Using new Google reCAPTCHA with PHP
回答by Yerke
I liked Levit's answer and ended up using it. But I just wanted to point out, just in case, that there is an official Google PHP library for new reCAPTCHA: https://github.com/google/recaptcha
我喜欢 Levit 的回答并最终使用了它。但我只是想指出,以防万一,有一个用于新 reCAPTCHA 的官方 Google PHP 库:https: //github.com/google/recaptcha
The latest version (right now 1.1.2) supports Composer and contains an example that you can run to see if you have configured everything correctly.
最新版本(现在是 1.1.2)支持 Composer 并包含一个示例,您可以运行该示例来查看是否正确配置了所有内容。
Below you can see part of the example that comes with this official library (with my minor modifications for clarity):
下面你可以看到这个官方库附带的部分示例(为了清楚起见,我做了一些小的修改):
// 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
}
Hope it helps someone.
希望它可以帮助某人。
回答by Viktor Kashlyaev
In the example above. For me, this if($response.success==false)
thing does not work. Here is correct PHP code:
在上面的例子中。对我来说,这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
}
回答by Roshan Padole
To verify at server side using PHP. Two most important thing you need to consider.
使用 PHP 在服务器端进行验证。您需要考虑的两件最重要的事情。
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);
If you get $verifydata true, You done.
For more check out this
Google reCaptcha Using PHP | Only 2 Step Integration
如果你得到$verifydata true,你就完成了。
有关更多信息,请查看此
Google reCaptcha Using PHP | 仅需两步整合
回答by V? Minh
it is similar with mattgen88, but I just fixed CURLOPT_HEADER, and redefine array for it work in domain.com host server. this one doesn't work on my xampp localhost. Those small error but took long to figure out. this code was tested on domain.com hosting.
它与 mattgen88 类似,但我只是修复了 CURLOPT_HEADER,并重新定义数组使其在 domain.com 主机服务器中工作。这个在我的 xampp 本地主机上不起作用。那些小错误却花了很长时间才弄明白。此代码已在 domain.com 托管上进行了测试。
$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';
}
回答by Adam Kozlowski
Here you have simple example. Just remember to provide secretKey and siteKey from google api.
这里有一个简单的例子。请记住从 google 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>
回答by Code Spy
Source Tutorial Link
源教程链接
V2of Google reCAPTCHA.
V2的谷歌验证码。
Step 1- Go to Google reCAPTCHA
第 1 步- 转到Google reCAPTCHA
Login then get Site Keyand Secret Key
登录然后获取站点密钥和密钥
Step 2- Download PHP code hereand upload srcfolder on your server.
第 2 步-在此处下载 PHP 代码并在您的服务器上上传src文件夹。
Step 3- Use below code in your form.php
第 3 步- 在form.php 中使用以下代码
<head>
<title>FreakyJolly.com Google reCAPTCHA EXAMPLE form</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<?php
require('src/autoload.php');
$siteKey = '6LegPmIUAAAAADLwDmXXXXXXXyZAJVJXXXjN';
$secret = '6LegPmIUAAAAAO3ZTXXXXXXXXJwQ66ngJ7AlP';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$gRecaptchaResponse = $_POST['g-recaptcha-response']; //google captcha post data
$remoteIp = $_SERVER['REMOTE_ADDR']; //to get user's ip
$recaptchaErrors = ''; // blank varible to store error
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp); //method to verify captcha
if ($resp->isSuccess()) {
/********
Add code to create User here when form submission is successful
*****/
} else {
/****
// This variable will have error when reCAPTCHA is not entered correctly.
****/
$recaptchaErrors = $resp->getErrorCodes();
}
?>
<form autcomplete="off" class="form-createuser" name="create_user_form" action="" method="post">
<div class="panel periodic-login">
<div class="panel-body text-center">
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="text" autcomplete="off" class="form-text" name="new_user_name" required="">
<span class="bar"></span>
<label>Username</label>
</div>
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="text" autcomplete="off" class="form-text" name="new_phone_number" required="">
<span class="bar"></span>
<label>Phone</label>
</div>
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="password" autcomplete="off" class="form-text" name="new_user_password" required="">
<span class="bar"></span>
<label>Password</label>
</div>
<?php
if(isset($recaptchaErrors[0])){
print('Error in Submitting Form. Please Enter reCAPTCHA AGAIN');
}
?>
<div class="g-recaptcha" data-sitekey="6LegPmIUAAAAADLwDmmVmXXXXXXXXXXXXXXjN"></div>
<input type="submit" class="btn col-md-12" value="Create User">
</div>
</div>
</form>
</body>
</html>