Example code of Google Recaptcha implementation with php curl

Example code of Google Recaptcha implementation with php curl

Google reCaptcha is the most used captcha for preventing spam on web forms. Its a very useful thing to keep website, specially the forms which works with data. If you want to know more about recaptcha, please visit the reCaptcha website.

Installing and using reCaptcha is easy and google already has a very informative documentation on installation and usage. You can get started from the google documentation.

In this article, I’ll share a complete source code of an implementation of google reCaptcha in a web form. You’ll be able to take that code, replace with your info and use it right away. Let’s get started.

Frontend:

The frontend part is very simple. Here we have nothing to do with php at all. You just have to include a javascript file on head section and add a div inside of your form to have the captcha appear on your form. The following code is taken from Google’s Documentation which describes how you can handle the frontend display part:

<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha" data-sitekey="your_site_key"></div>
      <br/>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

Backend:

Backend part requires some custom work as it involves sending request to google server to verify the request. However, Its not that complicated. We can use curl request to verify the request and then proceed according to the output.

Code:

The example code is available on github, please follow the link below to get it and start using for your next project.

View Code on Github

 

Leave a Reply

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