Friday 2 November 2018

reCAPTCHA V3 Example in PHP


<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
## reCAPTCHA V3 key define ##
#client-side
define('RECAPTCHA_SITE_KEY', 'reCAPTCHA_site_key'); // define here reCAPTCHA_site_key
#server-side
define('RECAPTCHA_SECRET_KEY', 'reCAPTCHA_secret_key'); // define here reCAPTCHA_secret_key

class Captcha {
public function getCaptcha($SecretKey) {
$data = array(
'secret' => RECAPTCHA_SECRET_KEY,
'response' => $SecretKey
);
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($verify, CURLOPT_POST, true);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
$response_data = curl_exec($verify);
$response_data = json_decode($response_data);
curl_close($verify);
//echo "<pre>"; print_r($response_data); echo "</pre>";
return $response_data;
}
}

///////////////////////////// OR /////////////////////////////
/*
class Captcha {
public function getCaptcha($SecretKey) {
$Resposta = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . RECAPTCHA_SECRET_KEY . "&response={$SecretKey}");
$Retorno = json_decode($Resposta);
return $Retorno;
}
}
*/

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//echo "<pre>"; print_r($_REQUEST); echo "</pre>";
$ObjCaptcha = new Captcha();
$Retorno = $ObjCaptcha->getCaptcha($_POST['g-recaptcha-response']);
//echo "<pre>"; print_r($Retorno); echo "</pre>";
if ($Retorno->success) {
echo '<p style="color: #0a860a;">CAPTCHA was completed successfully!</p>';
} else {
$error_codes = 'error-codes';
if (isset($Retorno->$error_codes) && in_array("timeout-or-duplicate", $Retorno->$error_codes)) {
$captcha_msg = "The verification expired due to timeout, please try again.";
} else {
$captcha_msg = "Check to make sure your keys match the registered domain and are in the correct locations.<br> You may also want to doublecheck your code for typos or syntax errors.";
}
echo '<p style="color: #f80808;">reCAPTCHA error: ' . $captcha_msg . '</p>';
}
}
?>

<div class="contact_form">
<div class="" style="margin-top:0px;margin-bottom:15px;">
<div class="" style="width:50%">
<form id="Form1" name="Form1" action="" method="POST">
<label for="fname">First Name*</label><br>
<input type="text" name="fname" id="fname" required autofocus><br><br>

<label for="lname">Last Name*</label><br>
<input type="text" name="lname" id="lname" required><br><br>

<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"><br>
<input type="submit">
</form>
</div>
</div>
</div>

<script src="https://www.google.com/recaptcha/api.js?render=<?php echo RECAPTCHA_SITE_KEY; ?>"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('<?php echo RECAPTCHA_SITE_KEY; ?>', {action: 'homepage'}).then(function (token) {
document.getElementById('g-recaptcha-response').value = token;
});
});
</script>
</body>
</html>

23 comments:

  1. thank you so much!!! I've been looking for exactly this.

    ReplyDelete
  2. Also If you want to use cURL You should use belove class script:

    class Captcha{
    public function getCaptcha($SecretKey){
    $data = array(
    'secret' => RECAPTCHA_SECRET_KEY,
    'response' => $SecretKey
    );
    $verify = curl_init();
    curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
    curl_setopt($verify, CURLOPT_POST, true);
    curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
    $response_data = curl_exec($verify);
    $response_data = json_decode($response_data);
    curl_close($verify);
    /*var_dump($response_data);*/
    return $response_data;
    }
    }

    ReplyDelete
  3. Cant seem to get this to work, recieving error: missing-input-response. What to do?

    ReplyDelete
    Replies
    1. Replace this javascript:

      function grecaptcha_execute(){
      grecaptcha.execute('', {action: 'homepage'}).then(function(token) {
      document.getElementById('g-recaptcha-response').value=token;
      });
      }
      grecaptcha.ready(function() {
      grecaptcha_execute();
      });
      // On submit get any error recall grecaptcha_execute(); function

      Delete
    2. Unfortunately still having the same error after changing the javascript to the one above. It seems like response = $SecretKey does nothing. Where is $SecretKey value extracted from?

      Delete
    3. Could you send me your code or URL?

      Delete
    4. URL is: https://www.grontulien.no/recaptcha-v3-verify

      You can find the code here: https://drive.google.com/file/d/1oJFPooqn4B5Bjk82g5wWG0TGOSQnEcDa/view?usp=sharing

      It should be exatcly the same code as in this blog post, except for the keys which I entered.

      Delete
  4. URL is: https://www.grontulien.no/recaptcha-v3-verify

    You can find the code here: https://drive.google.com/file/d/1oJFPooqn4B5Bjk82g5wWG0TGOSQnEcDa/view?usp=sharing

    It should be exatcly the same code as in this blog post, except for the keys which I entered.

    ReplyDelete
  5. Please check this: https://prnt.sc/lsbase
    :)

    ReplyDelete
  6. Worked perfectly! Good job and thanks

    ReplyDelete
  7. In three days of banging my head up against recaptcha v3, this is the ONLY example I have found that is complete, make sense, AND works! Thank you!

    ReplyDelete
    Replies
    1. Thank you so much for reading my blog...!!!
      Please keep reading my blog...

      Delete
  8. Wow my friend..It is working fine. Thank you very much for saving my extra R&D time.....:)

    ReplyDelete
  9. How do i get the latest values of fname and lname in PHP? It would be nice if I get them in the part which says "CAPTCHA was completed successfully!" so I can mail those or put in the database.

    ReplyDelete
    Replies
    1. Hello Mich.

      Please use and try this code for insert latest fname and lname in databse.


      ## reCAPTCHA V3 key define ##
      #client-side
      define('RECAPTCHA_SITE_KEY', 'reCAPTCHA_site_key'); // define here reCAPTCHA_site_key
      #server-side
      define('RECAPTCHA_SECRET_KEY', 'reCAPTCHA_secret_key'); // define here reCAPTCHA_secret_key

      class Captcha {
      public function getCaptcha($SecretKey) {
      $data = array(
      'secret' => RECAPTCHA_SECRET_KEY,
      'response' => $SecretKey
      );
      $verify = curl_init();
      curl_setopt($verify, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
      curl_setopt($verify, CURLOPT_POST, true);
      curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
      curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
      curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
      $response_data = curl_exec($verify);
      $response_data = json_decode($response_data);
      curl_close($verify);
      return $response_data;
      }
      }

      $servername = "localhost";
      $username = "username";
      $password = "password";
      $dbname = "myDB";

      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);
      // Check connection
      if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
      }

      if ($_SERVER['REQUEST_METHOD'] == 'POST') {
      $ObjCaptcha = new Captcha();
      $Retorno = $ObjCaptcha->getCaptcha($_POST['g-recaptcha-response']);
      if ($Retorno->success) {
      // echo 'CAPTCHA was completed successfully!';

      ###### PUT IN THE DATABASE ######
      $fname = $_POST['fname'];
      $lname = $_POST['lname'];
      $sql = "INSERT INTO $dbname (firstname, lastname) VALUES ($fname,$lname)";

      if ($conn->query($sql) === TRUE) {
      echo "New record created successfully";
      } else {
      echo "Error: " . $sql . "
      " . $conn->error;
      }

      } else {
      $error_codes = 'error-codes';
      if (isset($Retorno->$error_codes) && in_array("timeout-or-duplicate", $Retorno->$error_codes)) {
      $captcha_msg = "The verification expired due to timeout, please try again.";
      } else {
      $captcha_msg = "Check to make sure your keys match the registered domain and are in the correct locations.
      You may also want to doublecheck your code for typos or syntax errors.";
      }
      echo 'reCAPTCHA error: ' . $captcha_msg;
      }
      }


      I you have any query then contact me.

      Delete
  10. I want the code and it works. But can you write it the same ,instead use the curl ,because I think the curl would work much better. Thank you

    ReplyDelete
  11. From where i can get recaptcha key

    ReplyDelete
    Replies
    1. You need to add your domain https://www.google.com/recaptcha/admin/create
      then you can get key.

      Delete
  12. I am implementing Google reCAPTCHA V3. What should i verify? Please explain

    ReplyDelete
    Replies
    1. Read this Guides: https://developers.google.com/recaptcha/docs/v3

      Delete
  13. This comment has been removed by a blog administrator.

    ReplyDelete