bbcompent1
bbcompent1

Reputation: 494

Integrating Google re-captcha in PHP existing form

Ok, I've been banging my head against the wall trying to figure this out on my own, but have had no success. I am trying to get recaptcha to validate the captcha on the same page. I would rather have it check that the captcha is right before proceeding to the next page. I placed the call for the google js file in the head:

<script src='https://www.google.com/recaptcha/api.js'></script>

Then following the instructions I place the second piece at the end of the form like so:

<div class="g-recaptcha" data-sitekey="***************************************"></div>

So far so good. Now, the part that is kicking my *** is the server side integration. The code they supply is:

When your users submit the form where you integrated reCAPTCHA, you'll get
as part of the payload a string with the name "g-recaptcha-response". In 
order to check whether Google has verified that user, send a POST request
with these parameters:

URL: https://www.google.com/recaptcha/api/siteverify
secret (required)   **********************************************
response (required) The value of 'g-recaptcha-response'.
remoteip    The end user's ip address.

I am really stumped as to how that part is supposed to work, like where does it go actually? I have checkout.php submitting to billing-checkout.php. Does that second part go into billing-checkout.php? If so, how do I make it work exactly? I hate feeling like a noob but I am very frustrated by this whole thing. Any help would be appreciated, thanks!

Upvotes: 1

Views: 484

Answers (1)

Demnogonis
Demnogonis

Reputation: 3222

You'll have to make a cURL request to the supplied URL and either get a yay or a nay back.

<?php
$cp = curl_init("https://www.google.com/recaptcha/api/siteverify");
$fields = array(
    'secret' => YOUR_RECAPTCHA_PRIVATE_KEY,
    'response' => $_POST['g-recaptcha-response'],
    'remoteip' => $_SERVER['REMOTE_ADDR']
);
curl_setopt($cp, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cp, CURLOPT_POST, 1);
curl_setopt($cp, CURLOPT_POSTFIELDS, $fields);
curl_setopt($cp, CURLOPT_TIMEOUT, 15);

$data = curl_exec($cp); // The response

curl_close($cp);

?>

Upvotes: 1

Related Questions