recaptchalib google example check php recaptcha

example - nuevo google recaptcha con casilla de verificación php del lado del servidor



recaptcha v3 php (11)

Acabo de configurar el nuevo Google recaptcha con casilla de verificación, funciona bien en el lado del sitio, sin embargo, no sé cómo hacerlo en el lado del servidor usando php, intenté usar el código anterior a continuación, pero el formulario se envía incluso si el No se utiliza recaptcha.

require_once(''recaptchalib.php''); $privatekey = "my key"; $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { $errCapt=''<p style="color:#D6012C ">The CAPTCHA Code wasnot entered correctly.</p>'';}


Seguridad de clave privada

Si bien las respuestas aquí funcionan definitivamente, están utilizando una solicitud GET , que expone su clave privada (a pesar de que se usa https ). En Google Developers, el método especificado es POST .

Para un poco más de detalle: https://.com/a/323286/1680919

Verificación vía POST

function isValid() { try { $url = ''https://www.google.com/recaptcha/api/siteverify''; $data = [''secret'' => ''[YOUR SECRET KEY]'', ''response'' => $_POST[''g-recaptcha-response''], ''remoteip'' => $_SERVER[''REMOTE_ADDR'']]; $options = [ ''http'' => [ ''header'' => "Content-type: application/x-www-form-urlencoded/r/n", ''method'' => ''POST'', ''content'' => http_build_query($data) ] ]; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); return json_decode($result)->success; } catch (Exception $e) { return null; } }

Sintaxis de matriz: uso la sintaxis de matriz "nueva" ( [ y ] lugar de array(..) ). Si su versión de php aún no lo admite, tendrá que editar esas 3 definiciones de matriz en consecuencia (ver comentario).

Valores devueltos: esta función devuelve true si el usuario es válido, false si no y null si se produjo un error. Puede usarlo, por ejemplo, simplemente escribiendo if (isValid()) { ... }


Enlace del tutorial de origen

V2 de Google reCAPTCHA .

Paso 1 - Ve a Google reCAPTCHA

Inicie sesión y luego obtenga la clave del sitio y la clave secreta

Paso 2 : descargue el código PHP https://github.com/google/recaptcha y cargue la carpeta src en su servidor.

Paso 3 : usa el código siguiente en tu formulario.php

<head> <title>FreakyJolly.com Google reCAPTCHA EXAMPLE form</title> <script src=''https://www.google.com/recaptcha/api.js''></script> </head> <body> <?php require(''src/autoload.php''); $siteKey = ''6LegPmIUAAAAADLwDmXXXXXXXyZAJVJXXXjN''; $secret = ''6LegPmIUAAAAAO3ZTXXXXXXXXJwQ66ngJ7AlP''; $recaptcha = new /ReCaptcha/ReCaptcha($secret); $gRecaptchaResponse = $_POST[''g-recaptcha-response'']; //google captcha post data $remoteIp = $_SERVER[''REMOTE_ADDR'']; //to get user''s ip $recaptchaErrors = ''''; // blank varible to store error $resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp); //method to verify captcha if ($resp->isSuccess()) { /******** Add code to create User here when form submission is successful *****/ } else { /**** // This variable will have error when reCAPTCHA is not entered correctly. ****/ $recaptchaErrors = $resp->getErrorCodes(); } ?> <form autcomplete="off" class="form-createuser" name="create_user_form" action="" method="post"> <div class="panel periodic-login"> <div class="panel-body text-center"> <div class="form-group form-animate-text" style="margin-top:40px !important;"> <input type="text" autcomplete="off" class="form-text" name="new_user_name" required=""> <span class="bar"></span> <label>Username</label> </div> <div class="form-group form-animate-text" style="margin-top:40px !important;"> <input type="text" autcomplete="off" class="form-text" name="new_phone_number" required=""> <span class="bar"></span> <label>Phone</label> </div> <div class="form-group form-animate-text" style="margin-top:40px !important;"> <input type="password" autcomplete="off" class="form-text" name="new_user_password" required=""> <span class="bar"></span> <label>Password</label> </div> <?php if(isset($recaptchaErrors[0])){ print(''Error in Submitting Form. Please Enter reCAPTCHA AGAIN''); } ?> <div class="g-recaptcha" data-sitekey="6LegPmIUAAAAADLwDmmVmXXXXXXXXXXXXXXjN"></div> <input type="submit" class="btn col-md-12" value="Create User"> </div> </div> </form> </body> </html>


Aquí tienes un ejemplo simple. Solo recuerde proporcionar secretKey y siteKey de google api.

<?php $siteKey = ''Provide element from google''; $secretKey = ''Provide element from google''; if($_POST[''submit'']){ $username = $_POST[''username'']; $responseKey = $_POST[''g-recaptcha-response'']; $userIP = $_SERVER[''REMOTE_ADDR'']; $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP"; $response = file_get_contents($url); $response = json_decode($response); if($response->success){ echo "Verification is correct. Your name is $username"; } else { echo "Verification failed"; } } ?> <html> <meta> <title>Google ReCaptcha</title> </meta> <body> <form action="index.php" method="post"> <input type="text" name="username" placeholder="Write your name"/> <div class="g-recaptcha" data-sitekey="<?= $siteKey ?>"></div> <input type="submit" name="submit" value="send"/> </form> <script src=''https://www.google.com/recaptcha/api.js''></script> </body>


En el ejemplo de arriba. Para mí, esto if($response.success==false) no funciona. Aquí está el código PHP correcto:

$url = ''https://www.google.com/recaptcha/api/siteverify''; $privatekey = "--your_key--"; $response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST[''g-recaptcha-response'']."&remoteip=".$_SERVER[''REMOTE_ADDR'']); $data = json_decode($response); if (isset($data->success) AND $data->success==true) { // everything is ok! } else { // spam }


En respuesta a la respuesta de @ mattgen88 , aquí hay un método CURL con una mejor disposición:

//$secret= ''your google captcha private key''; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => "https://www.google.com/recaptcha/api/siteverify", CURLOPT_HEADER => "Content-Type: application/json", CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => FALSE, // to disable ssl verifiction set to false else true //CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => array( ''secret'' => $secret, ''response'' => $_POST[''g-recaptcha-response''], ''remoteip'' => $_SERVER[''REMOTE_ADDR''] ) )); $response = json_decode(curl_exec($curl)); $err = curl_error($curl); curl_close($curl); if ($response->success) { echo ''captcha''; } else if ($err){ echo $err; } else { echo ''no captcha''; }


La mejor y más fácil solución es la siguiente.
index.html

<form action="submit.php" method="POST"> <input type="text" name="name" value="" /> <input type="text" name="email" value="" /> <textarea type="text" name="message"></textarea> <div class="g-recaptcha" data-sitekey="Insert Your Site Key"></div> <input type="submit" name="submit" value="SUBMIT"> </form>

submit.php

<?php if(isset($_POST[''submit'']) && !empty($_POST[''submit''])){ if(isset($_POST[''g-recaptcha-response'']) && !empty($_POST[''g-recaptcha-response''])){ //your site secret key $secret = ''InsertSiteSecretKey''; //get verify response data $verifyResponse = file_get_contents(''https://www.google.com/recaptcha/api/siteverify?secret=''.$secret.''&response=''.$_POST[''g-recaptcha-response'']); $responseData = json_decode($verifyResponse); if($responseData->success){ //contact form submission code goes here $succMsg = ''Your contact request have submitted successfully.''; }else{ $errMsg = ''Robot verification failed, please try again.''; } }else{ $errMsg = ''Please click on the reCAPTCHA box.''; } } ?>

He encontrado esta referencia y el tutorial completo desde aquí: uso del nuevo Google reCAPTCHA con PHP


Me gustó la respuesta de Levit y terminé usándola. Pero solo quería señalar, por si acaso, que hay una biblioteca oficial de Google PHP para el nuevo reCAPTCHA: https://github.com/google/recaptcha

La última versión (ahora 1.1.2) es compatible con Composer y contiene un ejemplo que puede ejecutar para ver si ha configurado todo correctamente.

A continuación puede ver parte del ejemplo que viene con esta biblioteca oficial (con mis pequeñas modificaciones para mayor claridad):

// Make the call to verify the response and also pass the user''s IP address $resp = $recaptcha->verify($_POST[''g-recaptcha-response''], $_SERVER[''REMOTE_ADDR'']); if ($resp->isSuccess()) { // If the response is a success, that''s it! ?> <h2>Success!</h2> <p>That''s it. Everything is working. Go integrate this into your real project.</p> <p><a href="/">Try again</a></p> <?php } else { // If it''s not successful, then one or more error codes will be returned. ?> <h2>Something went wrong</h2> <p>The following error was returned: <?php foreach ($resp->getErrorCodes() as $code) { echo ''<tt>'' , $code , ''</tt> ''; } ?></p> <p>Check the error code reference at <tt><a href="https://developers.google.com/recaptcha/docs/verify#error-code-reference">https://developers.google.com/recaptcha/docs/verify#error-code-reference</a></tt>. <p><strong>Note:</strong> Error code <tt>missing-input-response</tt> may mean the user just didn''t complete the reCAPTCHA.</p> <p><a href="/">Try again</a></p> <?php }

Espero que ayude a alguien.


No soy fanático de ninguna de estas soluciones. Yo uso esto en su lugar:

$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, [ ''secret'' => $privatekey, ''response'' => $_POST[''g-recaptcha-response''], ''remoteip'' => $_SERVER[''REMOTE_ADDR''] ]); $resp = json_decode(curl_exec($ch)); curl_close($ch); if ($resp->success) { // Success } else { // failure }

Yo diría que esto es superior porque se asegura de que se está PUBLICANDO en el servidor y no está haciendo una incómoda llamada ''file_get_contents''. Esto es compatible con recaptcha 2.0 descrito aquí: https://developers.google.com/recaptcha/docs/verify

Encuentro este limpiador. Veo que la mayoría de las soluciones son file_get_contents, cuando siento que curl sería suficiente.


Para verificar en el lado del servidor usando PHP. Dos cosas más importantes que debes tener en cuenta.

1. $_POST[''g-recaptcha-response''] 2.$secretKey = ''6LeycSQTAAAAAMM3AeG62pBslQZwBTwCbzeKt06V''; $verifydata = file_get_contents(''https://www.google.com/recaptcha/api/siteverify?secret=''.$secretKey.''&response=''.$_POST[''g-recaptcha-response'']); $response= json_decode($verifydata);

Si obtiene $ Verifieddata true , ya lo hizo .
Para más información mira esto
Google reCaptcha usando PHP | Solo integración de 2 pasos


es similar con mattgen88, pero acabo de arreglar CURLOPT_HEADER y redefinir la matriz para que funcione en el servidor host de domain.com. este no funciona en mi xampp localhost. Ese pequeño error, pero tardó mucho en darse cuenta. este código fue probado en el alojamiento de domain.com.

$privatekey = ''your google captcha private key''; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify"); curl_setopt($ch, CURLOPT_HEADER, ''Content-Type: application/json''); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, array( ''secret'' => $privatekey, ''response'' => $_POST[''g-recaptcha-response''], ''remoteip'' => $_SERVER[''REMOTE_ADDR''] ) ); $resp = json_decode(curl_exec($ch)); curl_close($ch); if ($resp->success) { // Success echo ''captcha''; } else { // failure echo ''no captcha''; }


esta es la solución

index.html

<html> <head> <title>Google recapcha demo - Codeforgeek</title> <script src=''https://www.google.com/recaptcha/api.js''></script> </head> <body> <h1>Google reCAPTHA Demo</h1> <form id="comment_form" action="form.php" method="post"> <input type="email" placeholder="Type your email" size="40"><br><br> <textarea name="comment" rows="8" cols="39"></textarea><br><br> <input type="submit" name="submit" value="Post comment"><br><br> <div class="g-recaptcha" data-sitekey="=== Your site key ==="></div> </form> </body> </html>

verificar.php

<?php $email; $comment; $captcha; if(isset($_POST[''email''])) $email=$_POST[''email'']; if(isset($_POST[''comment''])) $comment=$_POST[''comment'']; if(isset($_POST[''g-recaptcha-response''])) $captcha=$_POST[''g-recaptcha-response'']; if(!$captcha){ echo ''<h2>Please check the the captcha form.</h2>''; exit; } $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER[''REMOTE_ADDR'']), true); if($response[''success''] == false) { echo ''<h2>You are spammer ! Get the @$%K out</h2>''; } else { echo ''<h2>Thanks for posting comment.</h2>''; } ?>

http://codeforgeek.com/2014/12/google-recaptcha-tutorial/