How to validate Google reCaptcha / noCaptcha in PHP?

4

How do I submit the POST that Google requests and thus make my field validated?

    
asked by anonymous 14.05.2015 / 21:32

2 answers

5

You send the POST method with the necessary data to google and receive content in PHP Array as follows:

    $captcha = $_POST['g-recaptcha-response'];
    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=<SUA SITE KEY>&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']), TRUE);

g-recaptcha-response is the $_POST variable your reCaptcha will create.

file_get_contents(...) is a function that executes the file and expects the file to return results for it. In this case we call a Google validator through the link and value the values it needs to operate and it returns the following in JSON :

{
  "success": true|false,
  "error-codes": [...]   // optional
}

json_decode('...', TRUE) turns object JSON into array PHP . If the second value (in the TRUE syntax) is FALSE we will get a object instead of array .

You can now validate like any other array in PHP :

if ($response['success'] == FALSE) {
        // Maldito spammer!
        return FALSE;
    } else {
        // Nice user
        return TRUE;
    }

Good studies! :)

    
14.05.2015 / 21:32
2

If it does not work with file_get_contents (as happened on the server in my hosting). There is a library in github, but I implemented it with cURL . It was basically like this:

# Os parâmetros podem ficar em um array
$vetParametros = array (
    "secret" => "SUA-CHAVE-SECRETA",
    "response" => $_POST["g-recaptcha-response"],
    "remoteip" => $_SERVER["REMOTE_ADDR"]
);
# Abre a conexão e informa os parâmetros: URL, método POST, parâmetros e retorno numa string
$curlReCaptcha = curl_init();
curl_setopt($curlReCaptcha, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($curlReCaptcha, CURLOPT_POST, true);
curl_setopt($curlReCaptcha, CURLOPT_POSTFIELDS, http_build_query($vetParametros));
curl_setopt($curlReCaptcha, CURLOPT_RETURNTRANSFER, true);
# A resposta é um objeto json em uma string, então só decodificar em um array (true no 2º parâmetro)
$vetResposta = json_decode(curl_exec($curlReCaptcha), true);
# Fecha a conexão
curl_close($curlReCaptcha);
# Analisa o resultado (no caso de erro, pode informar os códigos)
if ($vetResposta["success"]) echo "<p>Captcha OK!</p>\n";
else 
{
    echo "$<p>Problemas:</p>\n";
    foreach ($vetResposta["error-codes"] as $strErro) echo "$strTab<p>Erro: $strErro</p>\n";
}

I did not see any advantage in using the library, but if you want to see, there is a related article where I replied with both options.

    
10.12.2015 / 19:30