Skip to content

Instantly share code, notes, and snippets.

@LeonanCarvalho
Created July 2, 2019 15:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeonanCarvalho/60431916d72a041f207e44f15430d9f0 to your computer and use it in GitHub Desktop.
Save LeonanCarvalho/60431916d72a041f207e44f15430d9f0 to your computer and use it in GitHub Desktop.
ReCaptcha v3 php
<?php
/**
* Created by PhpStorm.
* User: Leonan Carvalho
* Date: 02/07/2019
* Time: 10:44
*/
//Valida se o método é post e se na requisição há o token do recaptcha
if ($_SERVER['REQUEST_METHOD'] === 'POST' && array_key_exists("g-recaptcha-response", $_REQUEST)) {
$postBody = array(
"secret" => "<<:YOUR RECAPTCHAV3 PRIVATE KEY:>>",
"response" => $_REQUEST['g-recaptcha-response'],
"remoteip" => $_SERVER['REMOTE_ADDR'], //Important
);
// Envia uma requisição à API do recaptcha
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postBody));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close($ch);
$response = json_decode($server_output);
if (isset($response->success)) {
$valid = $response->success;
//Vc pode validar por score também, um score normal de um usuário seguro é por volta de 0.7
if(isset($response->score) && $response->score < 0.7){
//$valid = false;
throw new Exception("Low score {$response->score}", 1);
}
if (!$valid) {
//$valid = false;
throw new Exception("Invalid captcha", 2);
}
} else {
$valid = false;
throw new Exception("Invalid response", 3);
}
} else {
$valid = false;
}
if($valid){
//Confirma o formulário
}
<form method="GET" action="javascript:alert('Are you a robot?');" id="my_form">
<!-- hint: o id desse elemento pode ser dinâmico, para evitar ataques do tipo CSRF -->
<div id="captcha_place" ></div>
<button id="topSubmit" type="submit">OK</button>
</form>
<script type="text/javascript">
grecaptcha.ready(function() {
console.info('Captcha Ready');
grecaptcha.execute('<<: RECAPTCHA PUBLIC KEY :>>', {action: 'votepage'}).then(function(token) {
console.info('Captcha Token Aquired');
//Libera o método do post
document.getElementById('my_form').method = 'POST';
document.getElementById('my_form').action = 'form.php';
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "g-recaptcha-response");
input.setAttribute("value", token);
document.getElementById("captcha_place").appendChild(input);
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment