체크 박스 서버 측 PHP가있는 새로운 Google recaptcha
방금 확인란을 사용하여 새 google recaptcha를 설정했지만 사이트 측에서 잘 작동하지만 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>';}
이것은 해결책이다
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 개발자 지정된 방법이다 POST
.
좀 더 자세한 정보 : https://stackoverflow.com/a/323286/1680919
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(..)
). 당신의 PHP 버전이 아직 이것을 지원하지 않는다면, 그에 따라 3 개의 배열 정의를 편집해야 할 것입니다 (주석 참조).
반환 값 : 이 기능은 반환 true
사용자가 유효한 경우, false
그렇지 않은 경우 및 null
오류가 발생합니다. 예를 들어 간단히 작성하여 사용할 수 있습니다.if (isValid()) { ... }
나는 이러한 솔루션의 팬이 아닙니다. 대신 이것을 사용합니다.
$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
이 클리너를 찾았습니다. 대부분의 솔루션이 file_get_contents라는 것을 알았습니다. 컬이 충분하다고 생각되면.
쉽고 최선의 해결책은 다음과 같습니다.
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.';
}
}
?>
여기에서이 참조와 전체 자습서를 찾았 습니다-PHP와 함께 새로운 Google reCAPTCHA 사용
나는 Levit의 대답을 좋아했고 결국 그것을 사용했습니다. 하지만 새로운 reCAPTCHA에 대한 공식 Google PHP 라이브러리가있는 경우를 대비하여 지적하고 싶었습니다. https://github.com/google/recaptcha
최신 버전 (현재 1.1.2)은 Composer를 지원하며 모든 것을 올바르게 구성했는지 확인하기 위해 실행할 수있는 예제를 포함합니다.
아래에서이 공식 라이브러리와 함께 제공되는 예제의 일부를 볼 수 있습니다 (명확성을 위해 약간의 수정 사항 포함).
// 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를 사용하여 서버 측에서 확인합니다. 고려해야 할 가장 중요한 두 가지입니다.
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 $를 , 당신이 다 .
자세한 내용은
PHP를 사용하는 Google reCaptcha | 2 단계 통합
mattgen88과 유사하지만 CURLOPT_HEADER를 수정하고 domain.com 호스트 서버에서 작동하도록 배열을 재정의합니다. 이것은 내 xampp localhost에서 작동하지 않습니다. 작은 오류이지만 알아내는 데 오랜 시간이 걸렸습니다. 이 코드는 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';
}
여기에 간단한 예가 있습니다. 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>
소스 튜토리얼 링크
V2 의 구글 reCAPTCHA를 .
1 단계 -Google reCAPTCHA로 이동
로그인 후 사이트 키 와 비밀 키 를 받으세요
2 단계 - 여기에서 PHP 코드를 다운로드 하고 서버에 src 폴더를 업로드 합니다.
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>
에 대한 응답으로 @ mattgen88 의 대답, 여기에 더 나은 배열과 CURL 방법은 다음과 같습니다
//$secret= 'your google captcha private key';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.google.com/recaptcha/api/siteverify",
CURLOPT_HEADER => "Content-Type: application/json",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => FALSE, // to disable ssl verifiction set to false else true
//CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array(
'secret' => $secret,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
)
));
$response = json_decode(curl_exec($curl));
$err = curl_error($curl);
curl_close($curl);
if ($response->success) {
echo 'captcha';
}
else if ($err){
echo $err;
}
else {
echo 'no captcha';
}
참고 URL : https://stackoverflow.com/questions/27274157/new-google-recaptcha-with-checkbox-server-side-php
'IT TIP' 카테고리의 다른 글
시작할 때 시작할 프로그램을 어떻게 설정합니까? (0) | 2020.11.02 |
---|---|
다음 두 줄의 실행 사이에 지연 추가 (0) | 2020.11.02 |
Redis 서버를 계속 실행하는 방법 (0) | 2020.11.02 |
Android Play 스토어의 베타 버전입니다. (0) | 2020.11.01 |
Pandas 시리즈에서 NaN 제거 (0) | 2020.11.01 |