Run PHP function after reCAPTCHA validation

Asked

Viewed 264 times

0

I am working on a script that queries an external API that returns the data in json, I am making the consultation using ajax, but I’m facing some security issues.

The query works perfectly, I just need to create a validation to avoid that these queries can be made outside the form, or even within the form but only after the validation of reCAPTCHA.

The script stayed that way:

function buscarDados(cpf){ 
    if(getCookie('tipo') == 1 || getCookie('tipo') == 2){
        recarregaDados();
        $("#divLoading").hide();
        return true;
    }
    $.ajax({        
        type: "GET",        
        dataType: 'json',   
        async: false,      
        url: "buscar.php?cpf=" + cpf,       
        success: function(data){
            if(data.status == 1){
                setCookie('dadosNome', data.nome, 1);
                setCookie('dadosSexo', data.genero, 1);
                setCookie('dadosNascimento', data.nascimento, 1);
                var nome = data.nome;   
                if(data.genero == 'M')
                    $("#sexo").val('Masculino');
                else
                    $("#sexo").val('Feminino');
                var tmp = nome.split(" ");          
                nome = tmp[0];          
                $("#datadenascimento").val(data.nascimento);            
                $("#inputFirstName").val(tmp[0]);           
                $("#inputLastName").val('');
                for(i = 1; i < tmp.length; i++){
                    if($("#inputLastName").val() != '')
                        $("#inputLastName").val($("#inputLastName").val() + ' ');
                    $("#inputLastName").val($("#inputLastName").val() + tmp[i]);
                }
                $("#nomeCPF").html(nome);     
                $("#divLoading").hide();
            }else{
                if(data.erroCodigo == '102')
                    alert("O CPF informado não existe nas bases de dados da Receita Federal!");
                else
                    alert("Não foi possível realizar a verificação do seu CPF.");
                setCookie('tipo', 0);
                window.location.reload();
                window.reload();
            }
        }, //END success        
        error: function(e){         
            alert("Oops! Não foi possível realizar a verificação do seu CPF.");  
            setCookie('tipo', 0);
            window.location.reload();
            window.reload();    
        } // END error    
    }); // END $.ajax
    return true;
}


var captchaValido = 0;  
var correctCaptcha = function(response) {       
    if(response.length == 0)            
        captchaValido = 1;      
    else            
        captchaValido = 2;  
};
var onloadCallback = function() {    
    grecaptcha.render('recaptcha_cpf', {      
        'sitekey' : 'CHAVE_RECAPTCHA', 'callback' : correctCaptcha    
    });    
    grecaptcha.render('recaptcha_cnpj', {      
        'sitekey' : 'CHAVE_RECAPTCHA', 'callback' : correctCaptcha    
    });  
}; 


$('#verifica_cpf').click(function () {      
        if(captchaValido == 0){         
            alert('Por favor marque a opção "Não sou um robô" para continuar.');            
            return false;       
        }       
        if(captchaValido == 1){         
            alert('Verifique o captcha pois não houve validação correta.');         
            return false;       
        }
        $('.dados_verificados').delay(500).slideDown(350);
}); 

The php file that performs the query in the API was this way:

if($_SERVER['HTTP_REFERER'] == 'url_que_faz_a_consulta' and $_GET['cpf']){

    if(isset($_GET['cpf'])){
        $url = 'https://url_api/cpf/' . $_GET['cpf'];
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $data = curl_exec($ch);
        curl_close($ch);
        echo $data;
    }

} else {

include("404.php");
exit;
}

Currently it will only trigger PHP when solving captcha, but I need PHP itself to also perform this check, checking whether captcha has actually been solved, accepting only one query for each time it is solved.

Is there any way to do that? Or some other way to include an alternative validation in PHP to avoid bot queries?

1 answer

1

Yes, do the recaptcha validation by PHP

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "secret=".$secret."&response=".$token_do_formulario."&remoteip=".$ip_do_usuario_opcional);
$return = json_decode(curl_exec($ch));

I recommend using recaptcha v3 to avoid the user having to type the characters. An example of a company using the v3 version of recaptcha is Itau. Link: https://www.itau.com.br/servicos/boletos/segunda-via/

  • If you choose to use v3 Google returns a score 0.0 to 1.0 according to the score you bar access or request a second check. If you have not used your form the Google Api returns { success: false ... and you can already bar access.

  • And how do I send verified data to PHP by . js?

  • I’m not with my computer at the moment, the night I give you a return, but basically the token generated by recaptcha you send to the backend along with Cpf, as Voce using GET would look something like this: url: "buscar.php?cpf=" + cpf + "&token=" + token. Another recommendation if possible use POST instead of GET. You never know if you have someone sniffing the network.

  • In my case it would be possible to send via POST in the same ajax that makes the sending via GET, how would it look? Thank you.

  • I’m sorry Wendler still doesn’t have time to make his example, I’m in college, I get home around 11:30. Regarding your question there is no need to use GET and POST, you can only use the post, alias I think it is not possible to use two methods at the same time.

Browser other questions tagged

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