Confundido en cuanto a por qué esto no funciona. Cuando se envía el formulario, aparece el mensaje de error, lo que significa que mi verificación de recaptcha ha fallado.
De mi formulario:
<div class="g-recaptcha" data-sitekey="(site-key)"></div>PHP:
if(isset($_POST['g-recaptcha-response'])){ $captcha=$_POST['g-recaptcha-response']; } $secretKey = "(secret-key)"; $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha); $responseKeys = json_decode($response,true); if(intval($responseKeys["success"]) === true) { echo '<h3>Thanks for your message!</h3>'; } else { echo '<h3>Error</h3>'; }La documentación de reCaptcha especifica específicamente que los parámetros para la solicitud a https://www.google.com/recaptcha/api/siteverify deben enviarse a través de POST. Puedes usar CURL para esto.
$ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify', CURLOPT_POST => true, CURLOPT_POSTFIELDS => [ 'secret' => $secretKey, 'response' => $captcha, 'remoteip' => $_SERVER['REMOTE_ADDR'] ], CURLOPT_RETURNTRANSFER => true ]); $output = curl_exec($ch); curl_close($ch); $json = json_decode($output); // check response...No use file_get_contents . Google sugiere usar solicitudes POST. Puede usar algo en las líneas de lo siguiente
$curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => array( 'secret' => $secretKey, 'response' => $captcha ) )); $response = curl_exec($curl); curl_close($curl); if(strpos($response, '"success": true') !== FALSE) { echo '<h3>Thanks for your message!</h3>'; } else { echo "<h3>Error</h3>"; }EDITAR
La respuesta de Yemiez (me acaba de llegar a la esquina) es mejor para manejar la parte de respuesta, usando la función json_decode .
EDITAR acaba de corregir un error tipográfico
if(isset($_POST['g-recaptcha-response'])){ $captcha=$_POST['g-recaptcha-response']; } $recaptcha_secret = '(secret-key)'; $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$captcha); $response = json_decode($response, true); if(!empty($response["success"])) { echo 'Thanks for your message!'; } else { echo 'Error'; }