Google reCAPTCHA tutorial

Google has announced new service to prevent spams and attacks to your website. They name it “NO CAPTCHA reCAPTCHA” . Google reCAPTCHA is designed to protect your website from spams and abuse.

In this tutorial i am going to show you how to integrate it into your website. For demo purpose i made one simple script. Please look at the demo.

LIVE DEMODOWNLOAD

Register your website and get Secret Key.

Very first thing you need to do is register your website on Google recaptcha to do that click here.

Login to your Google account and submit the form.

capcha1

Once submit, Google will provide you following two information.

  • Site key
  • Secret key

Integrate Google reCAPTCHA in your website.

To integrate it into your website you need to put it in client side as well as in Server side. In client HTML page you need to integrate this line before <HEAD> tag.

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

And to show the widget into your form you need to put this below contact form, comment form etc.

<div class="g-recaptcha" data-sitekey="== Your site Key =="></div>

When the form get submit to Server, this script will send ‘g-recaptcha-response’ as a POST data. You need to verify it in order to see whether user has checked the Captcha or not.

Sample project

Here is the HTML code for the simple form with comment box and submit button. On submit of this form we will use PHP in back-end to do the Google reCAPTCHA validation.

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>

This will generate this form.
google recaptcha form
On server side i am using PHP for now. So on Form submit request we will check the POST variable.

form.php
<?php
        $email;$comment;$captcha;
        if(isset($_POST['email'])){
          $email=$_POST['email'];
        }if(isset($_POST['comment'])){
          $email=$_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;
        }
        $secretKey = "Put your secret key here";
        $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);
        if(intval($responseKeys["success"]) !== 1) {
          echo '<h2>You are spammer ! Get the @$%K out</h2>';
        } else {
          echo '<h2>Thanks for posting comment.</h2>';
        }
?>

try out the demo to see how it works.

Further reading:

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

300 Comments

  1. This is incorrect usage of the captcha. You need to verify that the g-recaptcha-response variable sent (In your case by POST) is valid, not only that it exists. Anyone could just spoof any old value for that variable and completely bypass the captcha if you don’t.

  2. Thank you very much for the tutorial!!
    I am not great at this still struggling with the last step as my website will send an email when all is well.
    When will it show:
    echo ‘You are spammer ! Get the @$%K out’; ?

    As I am trying to either get:

    Please check the captcha form.
    OR
    “Your message has been sent”

    So I need to check captcha first and then send the email and thank them.

      1. Lol, I understand now. I have put in onto my website and it seems to bw working allthough I am not sure if the verify is working out the way it is supposed to. I may have to wait and find out.
        Again many thanks!

          1. Google is our friend 😉

            I sent you an mail through the website with a code question regarding this captcha. I hope you received it in good order.

          2. No, still not working properly. It does ask the recaptcha but fails on the form check now. So one can send emty forms when marking te the recaptcha. So if you can help me out…

          3. Thank you but I already had it working and when I added the recaptcha it stopped working. So my problem is not in validation but rather in conflicting commands. I will continue my search 🙂

  3. I have searched around the web – High and low but your tutorial is the most relevant one to the Google’s latest NO CAPTCHA reCAPTCHA implementation. Bravo and I’m starting to like your site! Keep up the good work. Cheers!

  4. I am trying to implement this into a website of mine, but PHP dumps a huge load of warning text onto the screen, including my private key! That should never happen! The error I get after that is “Failed to open stream: invalid argument.” I don’t think I’m doing anything different than you.

    1. I figured out the large error, it was related to port 443 being blocked in my firewall. However, now it always says the captcha was correctly entered. It always returns true. What might I have messed up now?
      And just for the future, do you know of a way to prevent PHP from displaying errors/warnings like that (containing my private key) to the world? I don’t want to disable errors… I like those… but if my host has an error and all of a sudden anyone loading a page could get the key printed on their screen?

  5. Hi! I’m getting ‘Notice: Undefined variable: captcha in *****************htdocslabfrontrecaptcha.php on line 11’ . I can’t seem to work it out.

  6. Thanks for the advice. I had to modify your code a bit to get it working:

    $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOURKEY&amp;response=".$captcha."&amp;remoteip=".$_SERVER['REMOTE_ADDR']);
             
    $obj = json_decode($response);
    if($obj-&gt;{'success'}==false){   
        //spam
    }else{
       //not spam
    }
      1. I keep getting this PHP Notice:

        Notice: Use of undefined constant success – assumed ‘success’

        For this bit of code:

        if ($response.success == true) {

        Any ideas how to fix this?

        1. By default PHP assume everything as string, as in case of JSON object stored in $response it still assume that $response is string and hence show you this notice. Try decoding this using

          $result=json_decode($result);

          and print $result.success. I always turn off the notice in PHP because unless it’s fatal error i don’t care 😉

        2. Forgot the second json_decode argument in second example.

          $response = json_decode($response, true);

          if($response[‘success’] == false){

          or

          $response=json_decode(file_get_contents(“https://www.google.com/recaptcha/api/siteverify?secret=–SECRET–&response=”.$captcha.”&remoteip=”.$_SERVER[‘REMOTE_ADDR’]), true);

          if($response[‘success’] == false){

    1. Yes Marcos,
      You need to call that API url using HTTP methods (GET or POST) which is available in both jQuery or AngularJS JavaScript library or you can do this using core JavaScript too.

  7. Hi. I am trying to use this new captcha in my website contact form. I am submitting the form using ajax and then sending mail using php. but i am not able to capture the response of g-captcha-response in my php code as its posted by ajax. let me know how to do that.Everytime it returns false only.

    Thanks.

    1. Hi Jay,
      if you are using jquery ajax then set ‘async’ to off because PHP takes little bit time to take response and while it doing that, your else condition may be sending response to Ajax.

  8. I’m using your code on a site that I have registered for ReCAPTCHA and I’m getting this error.

    Parse error: parse error, unexpected T_LNUMBER in /home/v/i/site/public_html/form.php on line 16

    Line 16:

    $response=file_get_contents(“https://www.google.com/recaptcha/api/siteverify?secret=”code-here”&response=”.$captcha.”&remoteip=”.$_SERVER[‘REMOTE_ADDR’]);

    (I have entered the secret code between quotes)

    I suspect I have made a basic error but I am unfamiliar with PHP so I’m hoping you will be able to help. Many thanks in anticipation.

    1. Hi Pete,
      Here is my code. I think there is some error in calling Google host from your machine.

      $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify
      [email protected]
      &response="
      .$captcha."
      &remoteip="
      .$_SERVER['REMOTE_ADDR']);
  9. Thanks for this. I used the html code you provided for a contact form i have but i can submit the form without entering the recaptcha. is this correct? How do i set it so the captcha is required.

    1. If you observe the php code. We are checking it at back-end however if you want to force it from front-end then you can use JavaScript and fetch g-captcha-response value and if is null force user to select it.

          1. Shahid Shaikh – you make a suggestion then when the guy asks how you ask what?. Read your own responses before replying.

  10. I have been fighting with this all day. I cannot seem to get access to the json object items in my PHP. I am decoding them, and when I write out the contents I am seeing:
    {
    “success”: false,
    “error-codes”: [
    “missing-input-response”
    ]
    }
    But I discovered that my conditional if($response.success==false) wasn’t firing, I tried to write out the result of $json[success] (and yes I decoded it into $json first), and I am not getting anything back at all.

    Has anyone else come across this?

    1. Hi David,
      Can you simply try this instead of Decoding object in PHP.

      $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
              if($response.success==false)
              {
                echo '<h2>You are spammer ! Get the @$%K out</h2>';
              }else
              {
                echo '<h2>Thanks for posting comment.</h2>';
              }

      Also please ensure PHP version which you are using.

      1. Thanks for your reply.
        I did that initially but that was when I noticed that the $response.success==false wasn’t firing when it should. So I have been trying to “read” the response object/array ever since. I can write out the whole thing, I just can’t access the individual values.

  11. I’m not getting an error code. When I write out the whole json response I get a “success” : false – this is what I expect, because in my testing I was trying it by not doing the captcha at all. So given that I didn’t do the captcha, I should get a false response – the problem is that the conditional statement isn’t recognising that it is false, and it isn’t doing the stuff it is meant to when the response is false. This is why I have been trying to read the success item explicitly. But when I do I get a null response from it even though I can see it when I write out the whole json returned string.

  12. I’ve got an existing php mailer form but can’t figure out where and how to include the code. And I can’t find more documentation on Google. I don’t use Json or anything, just plain html, css, jquery and a mailer.php…

  13. Hello Shahid
    I have been looking all over for a form that will submit to the server-side, instead of doing a page refresh.
    OK, I have been using the old version of reCaptcha for about 3 years now, and am wanting to move on to the new 2.0.
    My question for you is the following.
    (I am using ASP Classic, not PHP)

    In the old, we would pass this.

    recaptcha_challenge_field = Request(“recaptcha_challenge_field”)
    recaptcha_response_field = Request(“recaptcha_response_field”)
    recaptcha_private_key = “private key”
    recaptcha_public_key = “pulbic key”
    cTemp = recaptcha_confirm(recaptcha_private_key, recaptcha_challenge_field, recaptcha_response_field)
    if cTemp “” Then
    Incorrect
    else
    correct
    end if

    However, this is not longer valid with the new 2.0 system.
    What would be the alternative, for ASP that you have for PHP?
    Any idea’s would be great.

    Thanks and continue the good work.
    Wayne

    1. Hi Wayne,
      This captcha is from Google and as per their doc, what all you need to do is add the captcha DIV in front-end and send the g-captcha-response to ASP file, from ASP file call Google API with secret key and response and accordingly take action.

          1. I Shahid,

            your code to integrate recaptcha V2 in classic ASP can’t be downloaded from wayne link. any other opportunity to get it ? It would be so helpfull…

            Thanks…

            Laurent

          1. Link (‘carrzkiss_030441Google_reCaptcha2.zip ‘ ) still broken, have them Moreno or Wayne to send me?

        1. Hi, Wayne,

          I’ve seen that the code to integrate Recaptcha V2 in classic ASP has an error while downloading from your post, and I could see that.
          Can you send me this file carrzkiss_030441Google_reCaptcha2.zip ou repair the broken link ?

          Thanks to you ! It’ll be so helpfull !

  14. Im still trying to work code out. I got the capture to work but Im confused where do I enter the details for the email to go/subject and if there is a redirect to a emails was sent I can attach.

    Is it in the PHP where i see all the email/comment text. Just dont know which place to enter those details.

  15. Hi,

    I got it working but Im new to abit of code. What part of the code do I enter email destination after the captcha is done and if there is a section to direct to a “Thanks your email has been sent” page I have set up?

    Or if someone can redirect to another page about this would be appreciated.

    1. Hi, as you can see in PHP code, we are showing response depending upon status of captcha, now if captcha is true and you want to send an email then you can another PHP libraray like this one to send an email. Also to redirect it on another thank you page, use Header(“location : thankyou.php”); right after the captcha verification is successful via Google API.

  16. Thanks for your post.I need validation for a check box how to give validation for to check weather check box is checked or not in java script as same for ur post comment …. little bit urgent …

      1. i have taken into variable and also i have placed j query code for validation

        jQuery(“#submit”).click(function(e){
        var data_2;
        jQuery.ajax({
        type: “POST”,
        url: “http://codeforgeek.com/wp-content/themes/codeforgeek/google_captcha.php”,
        data: jQuery(‘#commentform’).serialize(),
        async:false,
        success: function(data) {
        if(data.nocaptcha===”true”){
        data_2=1;
        }else if(data.spam===”true”)
        {
        data_2=1;
        }
        else
        {
        data_2=0;
        }

        }
        });
        if(data_2!=0){
        e.preventDefault();
        if(data_2==1){
        alert(“Please check the captcha”);
        }else{
        alert(“Please Don’t spam”);
        }
        }else
        {
        jQuery(“#commentform”).submit
        }

        });

        but going into else part “Please Don’t spam”.i need to get into if condition “Please check the captcha”.

        1. You sure you are returning String as true and false or boolean ? Please check. if you are using my code, add following line.

           if($response.success==false)
                  {
                    echo "false"
                  }else
                  {
                    echo "true"
                  }
          1. yah i am using ur code and also i had placed ur code in google_captcha.php but now i am not getting any alert if i don’t check on googlerecaptcha. Before i used to get “Please Don’t Spam”. alert

          2. Okay.
            Please return values from PHP in JSON format and use it in jQuery.

            //send same for no value in g-captcha-response value.
            if($response.success==false)
                    {
                         $arr = array('spam' => 'true');
                         echo json_encode($arr);
                    }else
                    {
                         $arr = array('spam' => 'false');
                         echo json_encode($arr);
                    }
  17. Thanks for the tutorial. But, when the time is out, there will be “previous recaptcha ” appear. How can I handle it? perhaps, user will reload the page. pls

  18. hello admin,
    i have placed ur code in my application .Recapture works fine .but i am having one doubt when i doesn’t enter Recapture i need to get alert as “Please Check captcha” but i am getting “please Don’t Spam” . I have placed ur validation code but going into else condition part what shall i do to get into if condition part in ur validation part.

    jQuery(“#submit”).click(function(e){
    var data_2;
    jQuery.ajax({
    type: “POST”,
    url: “http://sendgiftstohyd.com/urns_web2/wp-content/themes/yourtheme/google_captcha.php”,
    data: jQuery(‘#reviews’).serialize(),
    async:false,
    success: function(data) {
    if(data.nocaptcha===”true”){
    data_2=1;
    }else if(data.spam===”true”)
    {
    data_2=1;
    }
    else
    {
    data_2=0;
    }

    }
    });
    if(data_2!=0){
    e.preventDefault();
    if(data_2==1){
    alert(“Please check the captcha”);
    }else{
    alert(“Please Don’t spam”);
    }
    }else
    {
    jQuery(“#reviews”).submit
    }
    });

  19. You rock! Searched up and down for working solution… after 4 hours of testing, found your elegant and simple solution… thank you!

  20. Thanks, I searched a lot for a normal code and just found yours! Is it ok that I changed the
    if($response.success===false){
    to
    if($response.”success”===false){
    ?

      1. It’s said
        Notice: Use of undefined constant “success” – assumed ‘“success”’ in D:xampphtdocsmyphp…..chat.php on line 106

        Notice: Array to string conversion in D:xampphtdocsmyphp..chat.php on line 106

          1. I don’t know how to code with JSON. I found some some information and made this:
            }else{
            $response = file_get_contents(“https://www.google.com/recaptcha/api/siteverify?secret=mysecretcode&response=”.$captcha.”&remoteip=”.$_SERVER[‘REMOTE_ADDR’]);
            $response = str_replace(“\”, “”,$response);
            $response = json_decode($response);
            if($response->success===false){
            echo “Az captcha érvényesítés nem sikerült!”;
            $captcha_data = true;
            }
            }

            If this not good to could you send the right code to my e-mail address?

  21. Hi Shahid,

    I am not a real programmer, just trying to keep the spam and attacks away from my site.
    I have integrated the code and feel I am most the way there but I am not sure I comletely understand how it works.

    At the moment I get either

    “Please check the captcha form” when form sent but captcha not ticked.

    Or

    “Your message has been sent” and I have echoed $response; and got “true” just to check, so ok, my email sends as well.

    However when I hit send after the captcha has been incorrectly completed and is highlighed red with incorrect answer I would expect the ” echo ‘You are spammer ! Get the @$%K out’; ?” case, but always get “Please check the captcha form”, ie captcha not ticked.

    So in essence I never get to see ‘You are spammer ! Get the @$%K out’; or a false instance of $response.success.

    I this how its supposed to work?
    When will it show:
    echo ‘You are spammer ! Get the @$%K out’; ?

    Many thanks for the tutorial Shahid, I feel I am nearly there

    Paul

    1. Hi Paul,
      It’s Google algorithm which runs on their Server will Return False then only You are Spammer will be true. I think if we try to simulate it for Humans it will be difficult. But i am sure Google deals with Bots about it. I hope you get it, It’s up to Google to deal with that, we don’t know when that response will come.

      1. Hi Shahid,

        So it would appear that my version of your code is working properly? That would be great news indeed.
        What is the best action to take for the false, you are spammer result?, redirect them away to another site? or? display a blank page or simple error message page?

        thanks

        Paul

      1. First, Thank you for answering me.
        I am learning, and here in my country Brazil, I have many friends who have this knowledge to help me.

        A note in your example, the php code form, is in a separate file, and is a comment form.

        On my site, the form of the code is on the same page of the form, and mine is a user registration form.

        I hope this information will help.

        Messagem on Browser when i open the page, i see only a white screen with te text below:
        Notice: Undefined variable: captcha in C:xampphtdocssistema_delaitvusuarios_cadastrar.php on line 140
        Please check the the captcha form.

        PHP CODE: (line 140 is the line 133 on pastebin)
        http://pastebin.com/6ntQeUkR

        FORM CODE:
        http://pastebin.com/BQbBR388

        tanks again.

        1. Your question is not erased. I just login to check the comments ! Sorry for late reply, can’t help in time difference. Any way , this error is coming because PHP is interpreting variable which is not been set yet which in your case will be set after form submission. Use isset() function to check whether the variable is set or not and then only do the proceeding in order to avoid this warning.

  22. Thank you for posting this example, was pulling my hair out trying to figure out why my PHP code was not working correctly.
    Really appreciated.
    Cheers,
    G

  23. I’m having a strange issue, my form is displaying the following error: invalid sitekey’. I’ve checked and i’m using the correct sitekey – any thoughts? Googles info doesn’t address how to resolve the error (i copied the sitekey from the no captcha recaptcha admin form – placing the secret key where it goes.

    any help or advice would be nice.

  24. Hi. Its a great one..
    How can I use it with javascript ajax call?
    When submits the form , the data along with captcha send to PHP side and validate it with secret code ?.
    How can I get the captcha data and to send via POST method to PHP server side.

    1. Use jQuery.Ajax function and send POST data of form to PHP file which we are doing in form submit. And in PHP send JSON response back to client depending upon Google verification.

  25. Yes i tried . But when i look into the output of “===> $response=file_get_contents(“https://www.google.com/recaptcha/api/siteverify?secret=”.$captcha.”&remoteip=”.$_SERVER[‘REMOTE_ADDR’]); <===", By printing the "$response"shows
    "
    {
    "success": false,
    "error-codes": [
    "missing-input-response",
    "invalid-input-secret"
    ]
    }
    "

    But when I print "$response.success" it shows
    "
    [{
    "success": false,
    "error-codes": [
    "missing-input-response",
    "invalid-input-secret"
    ]
    }]:success
    "
    I don't know what happened..Can you please show that code using ajax. Most of the above people also asking it.

  26. Hi,
    I have some problem, sometimes after klicking the recaptcha-checkbox the input for recaptcha code don’t popup, but the green check mark will appear immediately. What can I do?

  27. Thank you so much for the quick response.

    I have implemented the reCAPTCHA in the view so it is displaying on the page but I am not sure where to start with trying to verifying it.

    This is the controller function which the page uses:

    public function register(){

    $this->initialize($data);
    $data[‘submit_message’] =”;
    $this->load->model(‘utilities’);

    $this->form_validation->set_rules(‘username’, ‘Username’, ‘trim|required|min_length[5]|max_length[245]|callback_theusername_check’);

    $this->form_validation->set_rules(‘password’, ‘Password’, ‘trim|required|matches[confirmpassword]|min_length[5]|max_length[50]’);
    $this->form_validation->set_rules(‘confirmpassword’, ‘Password Confirmation’, ‘trim|required’);
    $this->form_validation->set_rules(’email’, ‘Email’, ‘trim|required|valid_email|callback_email_check’);
    $this->form_validation->set_rules(‘firstname’, ‘First name’, ‘trim|required’);
    $this->form_validation->set_rules(‘lastname’, ‘Last Name’, ‘trim|required’);
    $this->form_validation->set_rules(‘tc’, ‘Terms and Conditions’, ‘required’);

    if ($this->form_validation->run() == true)
    {

    $username = trim($this->input->post(‘username’));

    $password= trim($this->input->post(‘password’));
    $email= strtolower(trim($this->input->post(’email’)));

    //Extra inputs, etc

    }

    if ($this->form_validation->run() == true && $this->ion_auth->register($username, $password, $email))
    {
    $this->session->set_flashdata(‘message’, “Your user account has been created and you have been emailed an activation email.”);
    redirect(‘login’, ‘refresh’);
    }
    else
    {

    $this->data[‘message’] = $this->ion_auth->errors();

    $this->load->view(‘register’,$this->data);
    }
    }

    Please could you advise on how I would validate the recaptcha within this function. Any advice will be much appreciated, I am very new to this.

    Thank you

    1. Hi Ravi,
      Google returns data in JSON parse format. You can use it without Decode. If JSON returned as String then you need to decode it. Hope it clear the doubt.

  28. Thank you! Great post. Very clear example and easy to adapt to other needs.
    I took me a while to get rid of the PHP Notice and then I found the solution in the comments 😛

  29. Un grand merci pour ce tuto clair et précis même pour des “détails qui vont soit disant de soi” …
    MERCI et bon travail à vous.

  30. Just wanted to say thanks for posting this code. I’m a designer, not a programmer, so this helped a great deal! The Google instructions are a bit fuzzy (to me!) Thanks!!

  31. Shahid Shaikh thank you very much for the very helpful tutorial. I would like to ask you whether it can be implemented and validated using another language instead of php such as javascript or jquery? I’m not a programmer, however I have managed to implement it on my form (using IBM Domino Designer) but haven’t managed to validate it (via javascript getElementByID method) before submitting the form (users should not be able to submit the form if they haven’t checked the “I’m not a robot” option). Any help will be greatly appreciated.

    1. Hi,
      We can do this using jQuery or JavaScript. You need to check whether the post variable “g-recaptcha-response” is set or not and that will tell us whether user has selected the checkbox or not. Another important thing is calling Google captcha API Url to validate our “g-recaptcha-response” and that you can do using $.post variable of jQuery.

      Hope it helps.

      Thanks,
      Shahid.

  32. The script seems to set (!$capture) to true at first load and therefore exiting the script (‘Please check the the captcha form.’), in my case ignoring everthing that follows, includig script that is not related to recapture.

    1. Yes! I am also having this issue. Would be nice if someone could help. My footer is not appearing because of this issue, it seems to cut out the last part of my html code.

  33. After finishing my website, I asked a couple users to test it. I was using another CAPTCHA that seemed simple enough, but a few of them had issues with it due to their smaller devices. So I was on the hunt again for a new CAPTCHA when I came across your website. You laid everything clearly for using Google’s reCAPTCHA. Wonderful job. It’s refreshing to read, in layman’s terms, how to do something like this. You made it easy. Many thanks.

  34. I have implemented this and seems to work but I don’t get an email. Might be a silly question, but nowhere does it say where my form is being emailed to. Where do I indicate that?

    Also, I want to redirect a successful submission to a thank you page.

    Sorry, I am a designer, not a programmer so coding is not my strong suit.

  35. Hey, thank you ! but just one point, can you please make this example working?
    i mean, the php code is not finished… please add mailto() or phpmailer + 2files.
    ps. nice design.
    Tomas

  36. if you can get hold of the ‘g-recaptcha-response’ from the header/post, you can keep resending this and continue as a pass, due to it not being wiped or null’envoid on one use

  37. Hello, thanks for this tutorial, I have all day searching for something like this. However I got a problem. When i submit the form if does not go to the thank-you-page it shows the response code from google and receive the email in my account… Any idea why this is happening?

  38. I am working on this on ASP site and couldn’t find an example of the code in use. I seen that Wayne above linked to his site but it isn’t working at all. Any point in the right direction would be great.

    1. I believe you need to add a header “Access-Control-Allow-Origin” with a value of “*” generated on your localhost.

      If you’re using IIS, just add that header via IIS > Default Web Site > HTTP Response Headers > Add.

  39. Hi!
    I’m from Russia. My English is bad.
    But I very much want to thank you!
    Thank you very much!
    You helped me a lot!
    I’m looking for this information for a long time!

  40. Great script. Thank you.

    I have it working perfectly on Safari and Chrome. reCaptcha works, form gets submitted and the page re-directs properly to my thank you page.

    But on Firefox, the reCaptcha works and the form gets submitted. But instead of getting re-directed to the thank you page, the “echo ‘Thanks for posting comment.’;” code is keeping my success page from appearing. The form gets submitted, but the browser gets stuck.

    How can this be fixed?

  41. Hi, I have recreated your code into profile form but i’m getting this notice: Notice: Use of undefined constant success – assumed ‘success’ in C:xampphtdocstest.php on line 117, any idea why?

  42. Hi,

    I have the demo working and have managed to get a redirect working once successful but I cant get it to forward the captured information to an email address.

    I have included the coding you have here: http://codeforgeek.com/2014/11/phpmailer-ultimate-tutorial/

    All smtp settings are correct but when submitting it just goes to form.php as a blank page and does not send anything.

    Any help?

    Thanks

  43. Having a problem with noCaptcha on mobile. When users get the secondary test (e.g. click photos of food), they are returned to a place far below the noCaptcha widget. In one case, they are closer to a separate form in the footer than the form they need to submit. Is there a way to fix this so people receiving the secondary test on mobile always return to point of the form from which they started?

  44. Can you plz tell me how to do this reCaptcha with Register form and login form plz??
    Because i cant verify server side . I mean anyone can register my website without doing the reCaptcha check box. But i have the reCaptcha in my register.php page . the problem is in register_action.php file

  45. Hi
    This is the best write up i’ve found which does validate.

    However maybe a stupid question?

    How do I can change the form.php so that it sends the form to my email address?

    Can you please assist?

    Thanks Mark

  46. Great work on the post, it is really informative. But I was wondering if it’s okay to send a private key via a GET request? The reCaptcha Page “Verifying a User’s Response” indicates that the method for verification should be POST. Would it be safer to include the keys in a POST request (like it is with user credentials on a form)? Or does it not make a difference since it’s server side?

    Thanks!

  47. Thanks for the article. I got the recaptcha to work as your tutorial outlined. But I have not finished. My previous php file used the MAIL function to send the input of my form to my email address. So how do I get it to do this again. I am not a programmer or webmaster; just like to tinker, but I do maintain our website. Any suggestions or assistance would be greatly appreciated.

  48. What is the dot in if($response.success==false) supposed to mean?

    In PHP, $response is a string in JSON format, a dot is a string concatenation operator, and success is undefined, not even a variable because it doesn’t start with $.

    So, what is $response.success? What are we testing?

  49. What is the dot in if($response.success==false) supposed to mean?

    In PHP, $response is a string in JSON format, a dot is a string concatenation operator, and success is an unidentified name that is also invalid because it doesn’t start with $.

    So, what does that expression test?

      1. Here is some Classic ASP code to get and parse the captcha response (verion 2.0), using aspJSON to parse the JSON:

        captchaResponse = Request.Form(“g-recaptcha-response”)

        If captchaResponse “” Then
        set XmlObj = Server.CreateObject(“MSXML2.ServerXMLHTTP”)
        XmlObj.open “GET”, “https://www.google.com/recaptcha/api/siteverify?secret=” & secretKey & “&response=” & captchaResponse, false
        XmlObj.send

        googleResponse = XmlObj.responseText

        Dim oJSON
        Dim oItem
        Set oJSON = New aspJSON
        ‘Load JSON string
        oJSON.loadJSON(googleResponse)

        response.write(oJSON.data(“success”))

        If oJSON.data(“success”) Then
        passCheck = “True”
        End If

        End If

  50. Thanks for this, a great start for me but, sorry to ask a dumb question; how exactly do you get form results to an email address?
    I’ll guess ahead with ‘form processor’ which I guess is not covered in this tutorial?
    Sorry once again, I’m just really stuck, above my skillset.

  51. I have a problem with Google recaptcha. When i make a request to “g-recaptcha-response” it always return null. Do you know what might be the reason?

  52. Hi Shahid,
    even if I enter the secret key incorrectly or totally skips it, its still working, why is that? Is it only checking the existence of it or really verifying?
    By the much thanks for this tutorial!

    1. It actually verifies ! I am really not sure how does that working cause in demo i used same code and if i don’t pass keys it does’t show the form even ? How its working at your end ?

  53. This post saved my life. Thank you!!

    One question: Can I hide the million letters that get included in the email as the g-captcha response? I tried commenting out the two POST g-recaptcha-response lines in the php, but that prevented the recaptcha from working properly.

    Thank you!
    Maria

  54. Gosh, sorry, haha. It was an exaggeration. I mean the g-recaptcha response that is included in the email, for example:

    name: One Twenty
    lastname: PM
    company: Spas Company
    email: [email protected]
    address: 123 Street Tampa FL
    g-recaptcha-response: 03AHJ_Vut0cl930C2k89HSPNbXGJE1JtDRUhZ9rbUIltX477xiA7RcU5wIi4x57ojpS1-vnkEUYHD-FX0t41SEuGnmbjfVQVmCChYQn1qFsKGnVBoU88uzmEAAsXSHchrRY9F2Snl8QGj0pJijMLV32gqQCUsyDmZJafv-MWVOAZ6WjgX0-0jHkGiXqTzD1taODTlg2nBBqU7Sz0yg8Pj0bdnByaR5xpH5yV2t5o2mT6w6WGSbWXsuFCYnf6mVYzgt125UbhqjQttCnP2huNETq-qJUN6DR2OB0IDAg4HviTyC8JAw_8NOzIlDe7kQxwRFtevyQLICRbHMIX2hxgzl2WH0xhRYjGHtuaIzQpHMjHVz1cG8CrWMkh2sdoxOZ0dbNZqE9lGyHjedgfUV_1_L1zRODc4Q3hzn8gEcMc74GV7HscbxYrXOX90IdbqID9t-qdsoz6ZDYmsHZfOrEn8NLVFIYILBhpAFtNqG8FkhT1LdvtlHGoIc4YtxumkHY_qQst9P_kPUUdzZi8qjoOiwvUoPn7jgjcyJKlN0sr9DzdnLNcPMakeV–vSzwhMb_H2mWqOqG9sL5-UlQESdxGQIiZl1PduAgU8f9V9a_IYvvHreqjEUnMlHSkWrMDSSx2vJozweGWyZwX_OuTx_Pe8l8t_JX9tO8_6Vnmth9jyUca9Zxls9UMC_6V5agQrn5KUHrrRiPqWVjp5HQ0ZualHw3zXtbgieck97WUlgufFM-UlzWOQOaYsKq3wE5HTdDcXx0FlYaxtPqpcvmXCjtVRUehQWh9yGPJrxVHMtaJeA6aAY56eDL7I79zcv3LOejE5LfnWdsaoNKx0

    Can I hide the response that comes after “g-recaptcha-response: “?

  55. Also, I lied about one question. I have two.

    Second Q:
    I now keep getting a second step on the recaptcha, makes me choose specific photos after I click on “I’m not a robot”. This is while I test my work on the form. Could it be because it recognizes my IP as keep sending the form?

    Or is there something wrong with my code?

    http://dreammaker2016.com/testing-form.html

    Thank you!!

  56. sorry, I do not understand, I think it is very easy to cheat:

    I could do it with this form:

    I the same form than your demo with some changes:

    1 – change the form actio to http://demo.codeforgeek.com/google-captcha/form.php

    2 – remove this div:

    3 – replace removed div with following input:

    save that file and load on broswer, we are done, just submit that form, there is no captcha validation, I can click there as many time as I want, nothing will stop me.

    I did it mannually but I could program a robot to do the same hundreds time by minute.

    Your captcha validation is not working because you there is no validation on server side, just setting something on variable g-recaptcha-response on post request will make your captcha to fail and I will get your success message.

    please let me know if I am wrong or fix you script

    1. replace to my self: sorry, after send message code was removed, I will try explain again,

      to cheat it you need

      1 – replace action form to http://demo.codeforgeek.com/google-captcha/form.php

      2 – remove div with class g-recaptcha

      3 – instead of that div put an input text with name g-recaptcha-response

      just load that form on browser, and then complete form with spam text and send it. This happens because server side validation do not works

      M

  57. Hi, I have been chasing my tail for a couple days now…
    I was trying the captcha on my localhost and it working smoothly, but as soon as I get the code into the internet server…. file_get_content gets me a blank string.

    I can’t get the file_get_content to get me the json object, just a blank and therefore the validation can’t be done to see if it was right or not…

    any idea?

  58. Hello, I appreciate all the helpful tutorials you have posted. I cannot figure out how to accomplish sending mail after posting data from my form. I have the old reCaptcha working. It collects data from the forms and sends an email to the form owner, form user, sends email to both, and then updates a CVS file. When I implemented your code for the new “I am not a robot” reCaptcha everything works except no emails are sent. I am using the code below.

    I can send emails off line with the code if you are willing to assist.

    Thanks!

  59. it’s really cool and i tried the code and it helped me a lot, but after few tries i can pass the captcha without verification.

    if you add a value to #g-recaptcha-response by console you will pass it

    instead of

        if($response.success==false)
            {
              echo '<h2>You are spammer ! Get the @$%K out</h2>';
            }else
            {
              echo '<h2>Thanks for posting comment.</h2>';
            }

    you can do it like that

        if (strpos($response, "false") !== false) {
            echo "spam";  
        } else {
            echo "not spam";
        }
  60. yes, searching for the “false” or “true” string is more secure in this case. The original example didn’t work for me because you can’t drill down to the JSON string response.

    This function works:
    function validateCaptcha ($value) { $response=file_get_contents(“https://www.google.com/recaptcha/api/siteverify?response=”.$value.”&secret=***&remoteip=”.$_SERVER[‘REMOTE_ADDR’]);
    if(strpos($response,’false’)) {
    return false;
    } else {
    return true;
    }
    }

  61. Hi bro. I have a problem, do you kwon a metod that can I captured “some” in the iframe’s recaptcha when I have a http site? the iframe’s recaptcha its https protocol. I have incompatibility problems

  62. Hi, your tutorial has been very helpful…Thankyou!
    I am stuck with setting up the ReCaptcha fail error message to be on same page as the form. So if user doesn’t verify it doesn’t got to new page saying ‘Captcha Failed’ etc and they have to go ‘back’ and enter details again. My form is on html calling php.
    Many thanks

  63. Great site! Thank you so much for posting such useful stuff!

    I don’t understand where in the code my email is supposed to be. The code here seems to work except I don’t receive anything from the site.

    Thanks again,

    Eric

  64. Hi,

    Your script is EPIC 🙂 but i have a question:
    how can i add an error message if user didn’t checked a captcha?
    Please check the the captcha form.’
    Now this message opens in new window.. and that anoying.

  65. Thanks on your marvelous posting! I certainly enjoyed reading it,
    you might be a great author.I will make sure to bookmark yourr blog and will come
    back sometime soon. I want to encourage one to continue your
    great work, have a nice afternoon!

  66. i am inserting into a form i had setup previously. i cannot get it to go past “Please check the captcha form.” …. even when it is checked

  67. Got it to work. Was throwing out errors because php.ini had allow_url_fopen= off.
    Changed it to on and the errors went away.
    Thank you for the help.

  68. Hello,
    Thank you for this tutorial. i managed to use my form with google recaptcha without problem in my development environment.

    However when deploying to production environment. The form cannot be submitted, because recaptcha keep asking for the right code, even though right/correct code has been provided.

    Please help me. what might be wrong?

  69. Hello there, everything working well in my development environment. i managed to submit form after recaptcha validation and receive notification regarding it.

    However when the solution is deployed to production environment, the recaptcha seems not working, keep asking for right code, even though the code is right.

    What is wrong? Please help. Really appreciate!

  70. Hello shahid,

    Thanks for the code. I am using for my contact form. For some reason I can’t click on the recaptcha box. It won’t let you click on it? What am I doing wrong? Any help would be appreciated!

    Thanks
    Frank

  71. Hi. I am trying to just change the box width. My theme template allows me to put in custom CSS code but not sure how. I have the contact form within a 1/3 column and the recaptcha box overlaps and extends outside of the text box for the form. Thanks in advance

  72. thanks sahid for demo. but while selecting check box first time images are not loading, again user select check box again images popup loading. but i don’t want load images popup.

  73. Can this code of yours be pasted right on my web page where there’s already a form with ‘if/else’ code? For example, if certain fields are not filled, it will fail to send…
    Does this Captcha code stand alone as a ?php on the first lines, or do i need to somehow integrate it into the existing ?php that I have on my form already?

    1. Yes you can.

      All you need to do is add google recaptcha key in form and same validation like i did in FORM.php in your file where your form is getting submitted.

  74. Hello,
    i have a stupid question.

    I am using WordPress and i cannot make the plugin works. I arrived to the point where it shows up in the page but now i don’t know what to do, if i press “i’m not a robot” or don’t press it, it doesn’t matter, the message will arrive anyways.

    Where is have to put that programming part on server side? Basically i have no idea where the “response” part goes… sorry, never programmed anything in my life before.

    Sorry for the stupid question.

    1. Its ok and it is not a stupid question.

      I recommend you to refer this tutorial if you want to program it manually OR just go ahead and install this plugin in wordpress.

      1. Hello, thank you for your reply.

        I checked the tutorial and i already hit the first bump, i cannot find the function.php

        The page doesn’t exist.

        1. If you do not know WP folder structure i suggest you to go for plugin otherwise you may end up putting whole site down.

          1. It was my first thought but the free version of the plugin does not work with Contact Form 7… 🙁

          2. Yes, if you want the plugin work with Contact Form 7 you have to GoPro and pay.

            I downloaded their version of the contact form and the two plugins work fine, the only problem is that i have the same issue of before: wether i click the “i’m not a robot” or not, the email is sent anyways.

            Thank you for all your help by the way! Really appreciated.

    1. Make sure you have placed google keys correctly.

      If not, send me the email along with image of captcha you are selecting.

  75. where were you two hours ago when i was trying to make sense of that silly github example?

    seriously, *THANK YOU* ! i wish your example had better goggle ranking, it would have saved my morning.

    $response=file_get_contents(“https://www.google.com/recaptcha/api/siteverify?secret=”. $secret . “&response=” . $captcha . “&remoteip=”.$ip);

    pure brilliant !

      1. better yet, this page URL is now part of the comments of our php code, so you are now immortalized. you should feel honored !

    1. Hi Miguel,

      I will write tutorial on same using Node.js and PHP. Please give me some time.

      If you want to know about the process, use jQuery.ajaxForm if using JQuery to pass the google key in Backend and do the server side validation and return response. You need to change JavaScript code only, PHP one will stand same.

  76. Thanks so much for this super helpful tutorial! Google was NOT helpful… I’m still having some difficulty though. I’m finding that now, instead of mailing my fields, the only thing that is being sent is the recaptcha code (which is very long!). I’m wondering what I can do so that the recaptcha code is NOT sent by email and so that the other text fields do get sent instead. I’m using the go daddy webformmailer as the php file.

    Thank you for any help! I’ve been trying to figure this out for a while…

    1. Hey Katie,

      You need to separate the google recaptcha response key from email. I am sure its happening because emailer is sending every field which is in form. To remove, after the validation is been done with google, remove the g-captcha-response key from POST data.

  77. Thank you so much! I used the line unset($_POST[‘g-recaptcha-response’]); which got rid of the captcha code – hooray! But now it is posting a blank email with none of my fields.
    Essentially, all that I did was paste the code above to the top of my webformmailer form.
    Any idea of how to get the fields back?
    I feel like something is interferring with the ability of the formmailer to recognize and send then fields, but I can’t figure out what.
    Thank you for all of your help!

    1. Do one thing.

      Assign the fields which you want to send in email such as email address, subject and body to the variable and then delete google captcha response. Use those variables as a input to your emailer.

  78. Thank you very much, you are the only person I found which made a tutorial about this, and explained how to do it. The other ones just copy-paste google documentation!!

      1. I need help! I have a form form with recaptcha but it sent users out to the other page with words “Please check the the captcha form” when recaptcha doesn’t check. Question: I need when human doesn’t check recaptcha it write a message in front of it “Please re-enter your reCAPTCHA” in same page.

        Example My code form

        Send

        mai.php:
        <?php
        $email;$comment;$captcha;
        if(isset($_POST['email'])){
        $email=$_POST['email'];
        }if(isset($_POST['comment'])){
        $email=$_POST['comment'];
        }if(isset($_POST['g-recaptcha-response'])){
        $captcha=$_POST['g-recaptcha-response'];
        }
        if(!$captcha){
        echo 'Please check the the captcha form.’;
        exit;
        }
        $secretKey = “***********”;
        $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);
        if(intval($responseKeys[“success”]) !== 1) {
        echo ‘You are spammer ! Get the @$%K out’;
        } else {
        echo ‘Thanks for posting comment.’;
        }
        function send_mail()
        {
        $name = htmlspecialchars($_REQUEST[‘name’]);
        }
        {
        $email = htmlspecialchars($_REQUEST[’email’]);
        }
        $message = ‘Name: ‘.$_REQUEST[‘name’].’ E-mail: ‘.$_REQUEST[‘e_mail’].’Subgect: ‘.$_REQUEST[‘text’].”;

        include “class.phpmailer.php”;// подключаем класс

        $mail = new PHPMailer();
        $mail->CharSet = “UTF-8″;
        $mail->From = $_REQUEST[’email’];
        $mail->FromName = $_REQUEST[‘name’];
        $mail->AddAddress(‘[email protected]’);
        $mail->IsHTML(true);
        $mail->Subject = ‘Massege from *****’;

        if(isset($_FILES[‘files’]))
        {
        if($_FILES[‘files’][‘error’] == 0)
        {
        $mail->AddAttachment($_FILES[‘files’][‘tmp_name’],$_FILES[‘files’][‘name’]);
        }
        }
        $mail->Body = $message;
        if (!$mail->Send()) die (‘Mailer Error: ‘.$mail->ErrorInfo);
        {
        echo ”;
        echo ‘window.location.href=”thank-you.html”;’;
        echo ”;
        }
        if (!empty($_POST[‘submit’])) send_mail();
        ?>

  79. I need help! I have a form form with recaptcha but it sent users out to the other page with words “Please check the the captcha form” when recaptcha doesn’t check. Question: I need when human doesn’t check recaptcha it write a message in front of it “Please re-enter your reCAPTCHA” in same page.

    Example My code form

    Send

    mai.php:
    <?php
    $email;$comment;$captcha;
    if(isset($_POST['email'])){
    $email=$_POST['email'];
    }if(isset($_POST['comment'])){
    $email=$_POST['comment'];
    }if(isset($_POST['g-recaptcha-response'])){
    $captcha=$_POST['g-recaptcha-response'];
    }
    if(!$captcha){
    echo 'Please check the the captcha form.’;
    exit;
    }
    $secretKey = “***********”;
    $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);
    if(intval($responseKeys[“success”]) !== 1) {
    echo ‘You are spammer ! Get the @$%K out’;
    } else {
    echo ‘Thanks for posting comment.’;
    }
    function send_mail()
    {
    $name = htmlspecialchars($_REQUEST[‘name’]);
    }
    {
    $email = htmlspecialchars($_REQUEST[’email’]);
    }
    $message = ‘Name: ‘.$_REQUEST[‘name’].’ E-mail: ‘.$_REQUEST[‘e_mail’].’Subgect: ‘.$_REQUEST[‘text’].”;

    include “class.phpmailer.php”;// подключаем класс

    $mail = new PHPMailer();
    $mail->CharSet = “UTF-8″;
    $mail->From = $_REQUEST[’email’];
    $mail->FromName = $_REQUEST[‘name’];
    $mail->AddAddress(‘[email protected]’);
    $mail->IsHTML(true);
    $mail->Subject = ‘Massege from *****’;

    if(isset($_FILES[‘files’]))
    {
    if($_FILES[‘files’][‘error’] == 0)
    {
    $mail->AddAttachment($_FILES[‘files’][‘tmp_name’],$_FILES[‘files’][‘name’]);
    }
    }
    $mail->Body = $message;
    if (!$mail->Send()) die (‘Mailer Error: ‘.$mail->ErrorInfo);
    {
    echo ”;
    echo ‘window.location.href=”thank-you.html”;’;
    echo ”;
    }
    if (!empty($_POST[‘submit’])) send_mail();
    ?>

  80. Hello, is it possible tot have this

    if(!$captcha){
    echo ‘Please check the the captcha form.’;
    exit;
    }

    show at the same page, where the form is and other error alerts? How to do that?
    Thanks!
    Mary

  81. Hello Sergiy
    Allready found the solution? I had the same issue, so what I dis was

    put this

    if(!$captcha)$arrErrors[‘captcha’] = ‘your errortext.’;

    instead of this: if(!$captcha){
    echo ‘Please check the the captcha form.’;
    exit;
    }
    and add this into the captcha div: value=””
    it will stay on the same page. At least in my case.

  82. I have a problem!
    I hope that someone has the answer.
    My code always returns false, but if I past the content of $response directly on the browse, the answer is true….

  83. This has been very interesting, being new at this, I am trying to get a PHP response when valid, direct to another HTML page.

    Obviously the echo is not required, but this is what I have put in to get some direction for you

    <?php
    $email;$comment;$captcha;
    if(isset($_POST['email'])){
    $email=$_POST['email'];
    }if(isset($_POST['comment'])){
    $email=$_POST['comment'];
    }if(isset($_POST['g-recaptcha-response'])){
    $captcha=$_POST['g-recaptcha-response'];
    }
    if(!$captcha){
    echo 'Please Select the validation button first .’;
    exit;
    }
    $secretKey = “===SECRETKEY==”;
    $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);
    if(intval($responseKeys[“success”]) !== 1) {
    echo ‘You are spammer ! Get the @$%K out’;
    } else {
    a href=”http://www.MYWEBSITE.COM”;
    }
    ?>

  84. I am using form but not posting form in any case.i just call onSubmit=”return validateFrom()”
    function validateFrom(){
    //if error show error div

    //if no error called ajax, sent mail, save data and show success div.
    return false; // for each case
    }
    So how can handle recapture in this scenario.

  85. Thanks for your walkthrough man! This is the only one like it I could find. Was exactly what I was looking for. Got me up with my reCAPTCHA in about 5 minutes!

  86. Hmmm it looks like yohr site ate my first comment (it was super long) so I guess I’ll
    just summ it up what I had written and say, I’m thoroughly enjoying your blog.
    I too am an aspiring blog writer but I’m still
    new too everything. Do you have anyy suggestions for newbie blog writers?
    I’d definitely appreciate it.

  87. On some servers file_get_contents may not work and the response array from the verify url will be null. so in that case you have to use curl Get function to get the response.
    so script can be rewritten like this

    <?php
    $email;$comment;$captcha;
    if(isset($_POST['email'])){
    $email=$_POST['email'];
    }if(isset($_POST['comment'])){
    $email=$_POST['comment'];
    }if(isset($_POST['g-recaptcha-response'])){
    $captcha=$_POST['g-recaptcha-response'];
    }
    if(!$captcha){
    echo 'Please check the the captcha form.’;
    exit;
    }
    $secretKey = “Put your secret key here”;
    $ip = $_SERVER[‘REMOTE_ADDR’];
    $req_url = “https://www.google.com/recaptcha/api/siteverify?secret=”.$secretKey.”&response=”.$captcha.”&remoteip=”.$ip;
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$req_url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    $response=curl_exec($ch);
    curl_close($ch);
    $responseKeys = json_decode($response,true);
    if(intval($responseKeys[“success”]) !== 1) {
    echo ‘You are spammer !t’;
    } else {
    echo ‘Thanks for posting comment.’;
    }
    ?>

      1. Hi Jose and Shahid.

        This worked for me but i got a little confuse; the intval($responseKeys[“success”]) returned “0” when i put the correct reCAPTCHA but it returned “1” when i tried to log in without the captcha… is there anything wrong if it works that way?

        Thank you very much.

  88. Help please. I need to remove from the email received after the user verifies they are not a bot, the recaptcha code in the email Here is a sample of the code I am using (BTW not a programmer), can you help? Thanks in advance.

    $email;$comment;$captcha;
    if(isset($_POST[’email’])){
    $email=$_POST[’email’];
    }if(isset($_POST[‘comment’])){
    $email=$_POST[‘comment’];
    }if(isset($_POST[‘g-recaptcha-response’])){
    $captcha=$_POST[‘g-recaptcha-response’];
    }
    if(!$captcha){
    echo ‘Please check the the captcha form.’;
    exit;
    }
    $secretKey = “6Lc…CB_HhsKvxeC”; (shorted for security)
    $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);
    if(intval($responseKeys[“success”]) !== 1) {
    echo ‘You are a robot’;
    } else {
    echo ‘Please wait a moment’;
    }

      1. It doesn’t fail, however the code that it puts in the email becuase recaptcha is a part of an email submission form is too large and I need to know how to get rid of the code.

        1. I have the same exact issue. When i get an email after a form submission, I get this as part of a email:
          -g-recaptcha-response = 03AHJ_VutejIR2O0_ubE_qt6pV7UZ-SBUmsdI4Op8Ds-bGilarKlYFAbmIg5jqubwGhLIn7SkR7SMzOOQQXjC7xgjZY99_1UjkhRcarRfJC5BUNxYeGrqvlDrmpv8xDnJteTTlhbAbmoECUQ9fc6iUwtUKQBrad3UBpn3wsj6PiGRBH5AEvQggaEHhQrseAAN3Gi1LGpLRuWkvQNKYC04vIHnxtTr-akP12lh2Hc8M4nhJpmgcveDvFfNLx0knFK3m33r0yOGIYC8QF_DlBZ2Q2WIHxtf0zOn0hFx8bGlibKHb6rUaAe5MbdaZlmZasq7EwDS5isCzvJZ-ps73lo48PnucIKF2sDPlinvHrXC6Qs0_mT1_N9mKJK8c5s1ruIZh-uJOO4XR8o_g2-2stLIsZtX7OwzRXgJiqe61GX6e-6Jye8-gVwJctrVZF005bLlMMveA_27X0diIcOJB7Cvpp5BDfcy_t73clYjnsjuo9_OiZBrbemF1XuGTbmTulTG_uSHSrLrctmw39NAmhY4PABvMGbAhc5gce0zr4LnJwiwigfvL742IyKeSr13VO9kQW3IxmwwzEdd5WggBtCP8btpsliFxzryofzzs18Zvd9lx57IFcRGX7sCfs4ZmfpGqH_m8sKIULILHyYHQnSeckXtk8BcjaKqk9bH2DtMpzhRg0CbyMD6hKPIWLx52YA6THsIcbxY9hSnyFFhb2U20XVguM3Xgk-s6NhI8pobBAv52tLUw44db4lZ4XgkkfBGJJTQ1kHE0m3b39ZW5eNnkP67X_44KxEYO2XIr55660-4l2hPAVOpE_S8sewAzrAbLmA75msGIMhZKQhMB3D1D-_PXf2oP3HHuDtMgZSBh9hhdnnGW4qslZBymW-nnOzp6Q_XXXXXXXXXXXXXXX-W99vKbueVQT-7shaf2uEHpR2jZfqJJSBDSqPcVUwLSjSgKwloLAxLFdZTy 7VIOhEsZBFX9BuKjOb_XXXXXXXXXXXXXXXX1awqsGhx2T2u7zn3TlMQT_1esSHykrge0nEy3C_RWbOsixWzkqUSDanUGTxwW0sSimdYGg9_LvghsmqVKocFJb7nsKkOHaIrdE-P9tuJThsaArah62Fh_LTugLvlQN5NA
          -loggedin = true

          I changed parts of the string in case it was relevant to my server or API. I think the original poster of this question wants to hide this problem as much as I do. It is not needed in my emails that I read. As long as the server verify everything, that is cool by me. Why do I need such a long string to be produced in a email? Is there an easy way of hiding it in a email without breaking any code on the server?

  89. Hi,
    I want to display (!$captcha) message under the recaptcha filed.
    How can i display these empty message.
    I am also using ($_SESSION) but is not working, i can’t understand why.
    Please help me.
    —————————————————————————————-
    Form page
    ====

    form.php
    =======
    if(!$captcha){
    $_SESSION[“ReC”]= ‘Please check the the captcha form.’;
    header(“location:signup.php”);
    exit;
    }

  90. I want to skip the image verification process in recaptcha plugin.. can you pls help me to solve this problem

  91. I have an existing html form which uses php. I have tried for a couple of hours now to add the recaptcha verification code to this, but cannot get it to work correctly. I am not familiar enough with php. Could you assist?

  92. Howdy would you mind sharing which blog platform
    you’re working with? I’m going to start my
    own bkog in the near future but I’m having a hard
    time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The rsason I ask is because your layout seems differrent then most blogs and
    I’m looking for something unique. P.S Apologies for getting off-topic
    but I had to ask!

  93. I implemented your code examples and the responses work fine. Thank you. Your documentation was easy to follow. But how is the field information in my html file mailed from your form.php? My Post action was formerly to a Perl script in my cgi-bin. How do I get to my script from your form.php? I’m missing something. Thanks.

  94. Hi,

    file_get_contents() didn’t work on the production server i tried this code on so, I used a curl instead and it worked. If you could explain how to get file_get_contents() to work too.

    Heres the code that worked.
    $fields = array(
    ‘secret’ => $secretKey,
    ‘response’ => $captcha,
    ‘remoteip’ => $ip
    );
    $ch = curl_init(“https://www.google.com/recaptcha/api/siteverify”);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
    $response = json_decode(curl_exec($ch));
    if ($response->success)

  95. Hi, where does the infomation go when someone send the message? How do I get it to send to my email address?
    Thanks

  96. Hello there,
    Thanks for this great article ! I have a question about the second part, the php one. I saw that you created a form.php file.

    In my case, I bought a template and I installed it on WordPress. I manage to do the first part of your tuto, but when it comes to the php part, I don’t know where to put this code where you check the POST variable.
    I used Contact Form 7 to create my contact form. Then, I added the necessary codes for the Captcha to appear.
    But when it comes to add the php part, I’m lost. I don’t know where to put it ? Do you think I should put this code in the header.php page?

    Thanks in advance for your help 😉 Sorry for my english …

  97. My form sends whether or not I tick the recaptcha box. The integration instructions from google seem to be incomplete.

  98. Buenos dias a todos.

    les comento que hace muy poco tengo un incoveniente en el lugar donde trabajo, a la hora de abrir una pagina que adicionalmente carga el servicio recaptcha lo abre correctamente si el equipo tiene navegacion abierta, pero si le doy restriccion desde el servidor de seguridad firewall, me carga la pagina pero el recaptcha no aparece, he estado consultando y las opciones que me dan son habilitar un pull de ips pero no me serviria de nada porque mas a delante esas ips cambian y tendria el mismo problema, otra opcion es habilitar el dominio google.com, lo cual tampoco es conveniente, requeriria de poder averiguar que url exactamente utiliza este servicio de recaptcha, quisiera por favor si alguien tiene la manera de hacer visible este servicio que por favor comente.

    Muchas gracias.

  99. Good morning to all.

    I commented that very recently I have an inconvenience in the place where I work, when opening a page that additionally loads the service recaptcha opens correctly if the computer has open navigation, but if I give you restriction from the firewall firewall, I load the page but the recaptcha does not appear, I have been consulting and the options they give me are to enable a pull of ips but I would not use anything because more ahead those ips change and I would have the same problem, another option is to enable the domain Google.com, which is also not convenient, would require to be able to find out that url exactly uses this recaptcha service, please would you please if someone has the way to make visible this service that please comment.

    Thank you very much.

Leave a Reply

Your email address will not be published. Required fields are marked *