0

I have a problem with my Google recaptcha v2.

PHP Code:

<?php
  function reCaptcha($recaptcha){
  $secret = "SECRET KEY";
  $ip = $_SERVER['REMOTE_ADDR'];

  $postvars = array("secret"=>$secret, "response"=>$recaptcha, "remoteip"=>$ip);
  $url = "https://www.google.com/recaptcha/api/siteverify";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
  $data = curl_exec($ch);
  curl_close($ch);

  return json_decode($data, true);
}
?>

HTML Code in Head: <script src="https://www.google.com/recaptcha/api.js" async defer></script>

HTML Code in Body:

<form id="captcha" name="Captcha">
<div class="g-recaptcha" data-sitekey="6LfnSWEcAAAAAI4_e49TG2MCyMBSV6wFpSWEYQlF"></div>

<input id="submitForm" name="submitForm" class="submit_text" type="submit" value="Submit"/>    
</form>
<script>

button=document.getElementById("submitForm");
button.addEventListener('click', submitaction);

function submitaction() {
    
    <?php
    $recaptcha = $_POST['g-recaptcha-response'];
    $res = reCaptcha($recaptcha);
    
    if(!$res['success']) { ?>
    alert("Failed Captcha!");
    exit();
    <?php } ?>
}

For some reason, the code always returns "failed Captcha!". Can someone help me?

Regards!

j08691
  • 204,283
  • 31
  • 260
  • 272
Soda
  • 89
  • 1
  • 8
  • What does `var_dump($res);` look like? – ArSeN Sep 15 '21 at 19:47
  • PHP runs before the site is loaded, javascript after. That means when you load the page, submitaction only contains `alert("Failed Captcha!"); exit();`. Read up on ajax and how to properly submit an ajax form. – aynber Sep 15 '21 at 19:52

0 Answers0