Using reCAPTCHA with jQuery (ajax) and PHP

Asked

Viewed 2,816 times

2

Hello, Guys!

It’s been 4 days since I programmed using jQuery :)
I made a form using ajax and PHP, worked perfectly!
But...
the need to implement reCAPTCHA has arisen. I don’t know where to start, I need help.

html form.

<div id="alerta" class="alert alert-dismissible" role="alert" style="display: none;">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  <div><strong>Atenção!</strong> Existem campos obrigatórios.</div>
</div>

<form id="form" class="form-inline contact_box">
   <input type="text" class="form-control input_box" name="Nome">
   <input type="text" class="form-control input_box" name="Telefone">
   <input type="text" class="form-control input_box" name="Email">
   <input type="text" class="form-control input_box" name="Assunto">
   <textarea class="form-control input_box" name="Mensagem"></textarea>
   <div class="g-recaptcha" data-sitekey="6Ldf5kAUAAAAAFMK5xRr6aE06eiyx0nTRPqAYLHM"></div>
   <br>
   <button id="btnForm" type="submit" class="btn btn-default">Enviar</button>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
   $("#form").on("submit",function(){
      event.preventDefault();

      var dados = $(this).serialize();
      $.ajax({
        method: "POST",
        url: "https://meusite.com.br/enviaemail/",
        data: dados,
        beforeSend: function(){
         $('#btnForm').html('<i class="fa fa-spinner fa-pulse fa-fw"></i> Enviando...').attr("disabled", "disabled");
      },
      success: function(e){
        var retorno = JSON.parse(e);
        var tipo = retorno.tipo;
        var frase = retorno.frase;

        $('#alerta').addClass(tipo).find('div').html(frase);
        $('#alerta').show(500);

        $('#btnForm').html('<i class="fa fa-check" aria-hidden="true"></i> Enviado!').attr("disabled", false);
      }
    });
  });
</script>

enviaemail.php

<?php
  $nomeForm = $_POST['Nome'];
  $telsForm = $_POST['Telefone'];
  $emaiForm = $_POST['Email'];
  $assuForm = $_POST['Assunto'];
  $mensForm = $_POST['Mensagem'];

  if ($nomeForm != "" && $emaiForm != "" && $assuForm != "" && $mensForm != "") {
    if (filter_var($emaiForm, FILTER_VALIDATE_EMAIL)) {
      //função para enviar email...
      $Resp = array('tipo' => 'alert-success', 'frase' => 'Sua mensagem foi enviada com sucesso. Logo entraremos em contato.');
    } else {
      $Resp = array('tipo' => 'alert-warning', 'frase' => '<strong>Atenção!</strong> Por favor, insira um email válido.');
    }
  } else {
    $Resp = array('tipo' => 'alert-warning', 'frase' => '<strong>Atenção!</strong> Todos os campos são obrigatórios. Por favor, tente novamente.');
  }

  echo json_encode($Resp);
?>

The question is: how to do this send reCaptcha confirmation to PHP?

1 answer

5


To capture the value of reCaptcha, use the method getResponse. It will give you a code that should be used for validation.

In Javascript:

var dados = $(this).serialize();
post += "&recaptcha=" + grecaptcha.getResponse()
$.ajax({
    method: "POST",
    url: "https://meusite.com.br/enviaemail/",
    data: dados
});

In PHP (Using file_get_contents):

<?php

$content = [
    "secret" => "YOUR-SECRET",
    "response" => $_POST["recaptcha"] ?? "",
    "remoteip" => $_SERVER["REMOTE_ADDR"] ?? null,
];

$opts = [
    "http" => [
        "method" => "POST",
        "content" => http_build_query($content),
        "header" => "Content-Type: application/x-www-form-urlencoded",
    ]
];

$context = stream_context_create($opts);

$validation = file_get_contents("https://www.google.com/recaptcha/api/siteverify", FILE_BINARY, $context);

$response = json_decode($validation);

if ($response->success) {
    echo "Captcha válido";
} else {
    echo "Captcha inválido";
}

In PHP (Using Curl):

<?php

$content = [
    "secret" => "YOUR-SECRET",
    "response" => $_POST["recaptcha"] ?? "",
    "remoteip" => $_SERVER["REMOTE_ADDR"] ?? null,
];

$curl = curl_init("https://www.google.com/recaptcha/api/siteverify");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$validation = curl_exec($curl);
curl_close($curl);

$response = json_decode($validation);

if ($response->success) {
    echo "Captcha válido";
} else {
    echo "Captcha inválido";
}
  • Perfect! Thank you so much for the lesson.

  • You could implement this in a GET send?

  • @Wendler According to the documentation, only POST

  • I understood, I even posted a question to try something similar to this, if you have an idea: https://answall.com/q/385381/56902

Browser other questions tagged

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