Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google recaptcha response is null [PHP, localhost]

I need a little help for a problem with Google Recaptcha in a site I am developing in my pc (so localhost) before transferring to the open internet.

I signed up for Google Recaptcha and got a pair of keys. I created this form in a php page:

<div>
  <form action="" method="POST" name="formEmail">
    <section>
      <ul class="formMail" id="ulMsg">
        <li>
          <label for="msg">Messagge</label>
        </li><li>
          <textarea class="datoForm autoExpand" name="msg" id="msg" placeholder="Type Msg" rows='3' data-min-rows='3'></textarea>
        </li>
      </ul>
    </section>

    <div class="formMail" id="captchaContainer">
      <div class="g-recaptcha" data-sitekey="[Public_Key]"></div>
    </div>
    <br/><input type="button" value="Invia" onclick="formSubmit();">                            
  </form>
</div>

Instead of a submit button I call a JS file to validate user input, if everything is fine I submit data to another php page which checks captcha too. Source of this php page is:

if(isset($_POST['g-recaptcha-response'])){$captcha=$_POST['g-recaptcha-response'];}
$secretKey = "[Private_Key]";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);

Here is the problem: I don't get anything! I tried

var_dump($responseKeys);

but all I get is NULL. I do not get any other error, the captcha shows fine in the form and seems to work regularly. I am working in localhost, so my IP is 127.0.0.1, this should help but is useless. I do not have an "open" site to paste it and try, what am I doing wrong?

like image 917
SCdev Avatar asked Sep 13 '25 13:09

SCdev


1 Answers

Just had the same problem. It was a <div> tag causing the problem.

My form was within a main <div> used to format the general layout of the form. The <form> tag doesn't HAVE to be within the main <div> I was using for the form layout. I moved the <form> tag just before my form layout <div> tag and it started working perfectly.

The same can happen with <table> tags. You need to start the <form> tag before any tables used for formatting the form.

So your problem is the <div> just before the <form>:

<div> <form action="" method="POST" name="formEmail">

Just reverse the 2 tags and it will work fine:

<form action="" method="POST" name="formEmail"> <div>

like image 198
integriz Avatar answered Sep 16 '25 02:09

integriz