Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate Google reCAPTCHA v3 on server side?

I've just set up the new google recaptcha with checkbox, it's working fine on front end, however I don't know how to handle it on server side using PHP. I've tried to use the old code below but the form is sent even if the captcha is not valid.

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>';} 
like image 873
Moatez Avatar asked Dec 03 '14 14:12

Moatez


People also ask

How do I verify a Google reCAPTCHA?

The initial state, reCAPTCHA verification is required to proceed on this website. Click the checkbox to get a verification challenge. The checkbox has been clicked and a challenge is loading. You are instantly verified if the status changes to “You are verified”.

How do I know if my Google reCAPTCHA key is valid?

Google does not provide methods to verify site key, neither you can hack/access reCaptcha html code by JS since the reCapthca is in an iframe and frame's code is not programmatically accessible client-side. Its a common mistake to forget to update the allowable domains in the dashboard when pushing a new site live.


2 Answers

Private key safety

While the answers here are definately working, they are using a GET request, which exposes your private key (even though https is used). On Google Developers the specified method is POST.

For a little bit more detail: https://stackoverflow.com/a/323286/1680919

Verification via 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;     } } 

Array Syntax: I use the "new" array syntax ( [ and ] instead of array(..) ). If your php version does not support this yet, you will have to edit those 3 array definitions accordingly (see comment).

Return Values: This function returns true if the user is valid, false if not, and null if an error occured. You can use it for example simply by writing if (isValid()) { ... }

like image 57
Levite Avatar answered Sep 28 '22 15:09

Levite


this is solution

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> 

verify.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/

like image 25
SoCix Avatar answered Sep 28 '22 13:09

SoCix