Recaptcha error returns an error in file_get_contents

Asked

Viewed 520 times

1

inserir a descrição da imagem aqui

Hello guys, I’m having this problem with the recaptcha on a system implemented in PHP, the code below as this the code.

Recaptcha in HTML is like this, I decided to leave this script there also for organization.

<div class="g-recaptcha" id="captcha" data-sitekey="6LdAHWcUAAAAAPFO6j34mmWwhRer0K8Kp8901jM-" data-error-callback="errorRecaptcha" data-expired-callback="recaptchaExpired"></div>

                        <script>
                            // Função que bloqueia o submit quando o recaptcha expira
                            function recaptchaExpired(){
                                alert("ReCaptcha expirado, por favor verifique novamente !");
                                setTimeout(function(){location.reload()}, 500);
                            }

                            function errorRecaptcha(){
                                alert("Erro ao Validar Recaptcha");
                                setTimeout(function(){location.reload()}, 500);
                            }
                        </script>

is in PHP I perform this to validate

$captcha = $_POST['g-recaptcha-response'];
$secret_key = "***";

$content = http_build_query(array(
'secret' => $secret_key,
'response' => $captcha,
));

$context = stream_context_create(array(
'http' => array(
    'method' => 'POST',
    'content' => $content
)
));

//A função abaixo realiza o envio da resposta captcha para verificação e tem como retorno um JSON
$result_json = file_get_contents('https://www.google.com/recaptcha/api/siteverify', null, $context);

$array_result = json_decode($result_json, true);

//Valida se o retorno do servidor é true ou false para o captcha informado
$resp_captcha = intval($array_result['success']);
if ($resp_captcha === 1) {
  • Higor, if any answer has solved your problem you can mark as accepted by clicking on the green V side of the chosen points. Or, if you want, you can leave it open for a while if you want more alternatives, but it is good that after it is resolved you mark some to close the subject. Learn more in "How and why to accept an answer".

1 answer

2


Using Recaptcha on the site

As you did not accurately exemplify how your form is I will create an example of use with a login form:

<form action="login.php" method="post">
    <input type="text" name="username" placeholder="Digite o seu nome de usuário">
    <input type="password" name="password" placeholder="Digite a sua senha">
    <div class="g-recaptcha" data-sitekey="SUA-CHAVE"></div>
</form>

In the login.php you would have the following implemented logic:

// Aqui você recebe um valor fornecido pelo reCAPTCHA 
$captcha_code = $_POST['g-recaptcha-response'];

// Caso nenhum valor for recebido é porque o usuário nem respondeu o captcha
if (!$captcha_code) {
    echo "Por favor, responda o captcha.";
    exit;
}

// Se o usuário realmente respondeu o reCAPTCHA vamos fazer uma requisição para a API do captcha utilizando o file_get_contents do php

$resposta = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=SUA-CHAVE-SECRETA&response=".$captcha_code."&remoteip=".$_SERVER['REMOTE_ADDR']);
$resposta = json_decode($resposta, true);

// Lembre de colocar a sua chave secreta onde está SUA-CHAVE-SECRETA

// Agora vamos validar se realmente a resposta é válida

if ($answer_captcha['success'] == false) {
    echo "Você precisa provar que não é um robô.";
    exit;
} else {
    echo "Logado com sucesso!";
}

About the error, Google recommends, and it’s ideal that the validation is done on the server-side (it doesn’t even allow you to do it on the client-side). What you could do is take the answer from Captcha with Javascript and use in an AJAX call.

About this function below, you do not need to use it, because reCAPTCHA already validates if it is expired, all by accessing the API.

<script>

// Função que bloqueia o submit quando o recaptcha expira
function recaptchaExpired() {
    alert("ReCaptcha expirado, por favor verifique novamente !");
    setTimeout(function () {
        location.reload()
    }, 500);
}

</script>

In the documentation link below shows all the errors and what may cause.

Any questions access the Google Recaptcha documentation by clicking here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.