Validate Google's reCaptcha code from php using cURL

12,164

Solution 1

I managed to do it using file_get_contents, as I read in a related question. So I'll post my solution as an answer, for anyone who may be stranded like I was.

function verifyReCaptcha($recaptchaCode){
    $postdata = http_build_query(["secret"=>"XXXXXX","response"=>$recaptchaCode]);
    $opts = ['http' =>
        [
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        ]
    ];
    $context  = stream_context_create($opts);
    $result = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
    $check = json_decode($result);
    return $check->success;
}

The solution is extracted almost verbatim from here.

Solution 2

Sometimes you have to add this to your php.ini:

allow_url_fopen = 1 
allow_url_include = 1 
Share:
12,164
Christian Rodriguez
Author by

Christian Rodriguez

Updated on June 29, 2022

Comments

  • Christian Rodriguez
    Christian Rodriguez almost 2 years

    I'm trying to validate the reCaptcha code sent to my server using a cURL request. So far, this is the code:

    function verifyReCaptcha($conn,$recaptchaCode){
        $curl = curl_init("https://www.google.com/recaptcha/api/siteverify");
        $data = ["secret"=>"XXXXXX","response"=>$recaptchaCode];
        curl_setopt_array($curl, array(
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_HTTPHEADER => array('Accept: application/json'),
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $data));
        $resp = curl_exec($curl);
        curl_close($curl);
        if ($resp == NULL){
            echo "Error: ".curl_errno($curl);
        } else {
            echo $resp;
        }
    }
    

    The response that I'm getting is null, and the error it gives is sometimes 0, sometimes blank. So I'm completely at a loss here. How should it be coded to work properly?

    I'm following the documentation for reCaptcha here.

    EDIT: I've already tried the solution posted here, but it does not work for me.

  • Michael Chaney
    Michael Chaney almost 6 years
    What's the purpose of $conn?
  • Michael Chaney
    Michael Chaney almost 6 years
    One other thing - for your http_build_query you can also add this: "remoteip" => $_SERVER['REMOTE_ADDR']