Reputation: 690
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.
Upvotes: 4
Views: 18794
Reputation: 1131
Sometimes you have to add this to your php.ini:
allow_url_fopen = 1
allow_url_include = 1
Upvotes: 1
Reputation: 690
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.
Upvotes: 11