I don’t know what class you’re using for this, so I’m going to recreate this using the CURL, although there are other ways to do this.
I created a very simple function to do the service, without using official or existing libraries.
function isCaptchaValid(string $ChaveSecreta, $ClienteCaptcha, $ClienteIP) : bool {
$ClienteCaptcha = filter_var($ClienteCaptcha, FILTER_DEFAULT);
$ClienteIP = filter_var($ClienteIP, FILTER_VALIDATE_IP);
if($ClienteCaptcha && $ClienteIP){
$valoresPost = [
'secret' => $ChaveSecreta,
'response' => $ClienteCaptcha,
'remoteip' => $ClienteIP
];
$ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt_array($ch, [
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $valoresPost,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => 1,
CURLOPT_FAILONERROR => 1
]);
$resposta = json_decode(curl_exec($ch), true);
curl_close($ch);
if(isset($resposta['success'])){
return $resposta['success'];
}
}
return false;
}
That way just do, in HTML:
<form action="SuaPagina.php" method="post">
<div class="g-recaptcha" data-sitekey="SuaChavePublica"></div>
<input type="submit">
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>
While in PHP:
if(isset($_POST['g-recaptcha-response'])) {
//...
if(isCaptchaValid('SuaChavePrivada', $_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR'])){
echo 'Você preencheu o captcha corretamente :D';
exit;
}
}
echo 'Você errou o captcha! :(';
Remember if you are using Cloudflare, Sucuri, Incapsula (...) you should not use the REMOTE_ADDR
!
I tried to make the function as simple as possible, logically could do all the treatment creating other functions...
echo "<script>window.alert('".$erros_form[0]."');</script>';
- I feel like I’m missing a quote here. I know that’s not your problem, but it’s something I’ve noticed that’s wrong.– Victor Stafusa
Yes, thank you. It was my mistake when passing the code here.
– Leo
You are validating the request
post
. For some robots may not even go through your form and directly perform apost injection
– Gabriel Heming
I don’t work with PHP, but in a quick search I see that you check if the reCaptcha response is not null, but if you are using the class that Google makes available to check it returns an object with a field
success
, then you should check beyondnull
if you have the answer$response->success == true
– Leandro Godoy Rosa