2

I'm building a website with a form with reCAPTCHA check. As required from Google documentation, I've created a key for the target domain. Then, I've created a form containing reCAPTCHA section

HTML form

<form method="post" action="index.php">
   <div class="g-recaptcha" data-sitekey="PUBLIC_KEY"></div>
   <input type="submit" name="submit" />
</form>


PHP response check

When form is submitted, reCAPTCHA response is verified (in this example, it's simply printed).

$recaptcha = filter_input(INPUT_POST, 'g-recaptcha-response', FILTER_SANITIZE_STRING);
$googleurl = "https://www.google.com/recaptcha/api/siteverify";
$privatekey = "PRIVATE_KEY";
$remoteip = $_SERVER['REMOTE_ADDR'];

$curl = new Curl($googleurl."?secret=".$privatekey."&response=".$recaptcha."&remoteip=".$remoteip);
$response = json_decode($curl->exec(), true);

print_r($response);
die();

Curl is a class that simply builds a curl request and return result.

The problem

The snippet works fine online and I've checked $response values both with success and error cases. But during development, I must use it on localhost too. As stated in this post, all keys should work locally. But when I run the code, nothing is shown.

Community
  • 1
  • 1
Giorgio
  • 1,940
  • 5
  • 39
  • 64

1 Answers1

1

Though this question is older I post the answer because many people may run into the same problem. I think that this may be related to the general authentification problem with running reCaptcha on localhost which can be solved using secure token

I posted the solution here for reference

UPDATE - the working code:

For secure token generation I'm using slushie's php implementation

The PHP part:

<?PHP 

use ReCaptchaSecureToken\ReCaptchaToken as ReCaptchaToken;
require_once("libs/ReCaptchaToken.php");

//Generate recaptcha token
$config = [ 'site_key'      => 'place-your-site-key-here', 
            'site_secret'   => 'place-your-secret-key-here'
            ];
$recaptcha_token = new ReCaptchaToken($config);
$recaptcha_session_id = uniqid('recaptcha');
$recaptcha_secure_token = $recaptcha_token->secureToken($recaptcha_session_id);

?>

The HTML:

<html>
  <head>
  ...
    <script src='//www.google.com/recaptcha/api.js'></script>
  </head>
  <body>
    <form>
    ...
    <div class="g-recaptcha" data-sitekey="place-your-site-key-here" data-stoken="<?PHP echo $recaptcha_secure_token; ?>"></div>
    </form>
  </body>
</html>
Community
  • 1
  • 1
Hexodus
  • 12,361
  • 6
  • 53
  • 72