Skip Navigation
Madison, Wisconsin
Powderkeg Web Design
January 20, 2017

Easily Add Google's reCAPTCHA to Any Web Form to Help Prevent Spam

Matt
Matt
Easily Add Google's reCAPTCHA to Any Web Form to Help Prevent Spam

Combating spam is one of the never-ending tasks for anyone with an online presence. Thankfully, most email providers have become intelligent enough to hide most of it from us. But what happens when bots start attacking your website’s contact us form? To your email provider, this will look like legitimate submissions from your customers, but it’s the same as any spam email. Adding some form of “human verification” to your forms can help eliminate any spam submissions. The easiest to implement in my opinion is Google’s reCAPTCHA service. I will outline below how to add this to any of your websites.

  1. Register your site with reCAPTCHA by visiting this link.
  2. Google will generate two keys for you. A site key and a secret key. The site key can be used publicly, but the secret key should not be used publicly (hence the name!). In my example my two keys are:
    Site key: 6LeySRIUAAAAAJnYn_JKQ8i2UfH85wKA-YgSYACL
    Secret key: 6LeySRIUAAAAAM5d8huz1-SIW4OMjfgDx_pwfToe
  3. To add the reCAPTCHA to your form, paste the following within your <form> tag
    <!-- The script enqueue should ideally be in your <head> tag, but it still works if it's here -->
    <script src='https://www.google.com/recaptcha/api.js'></script>
    <div class="g-recaptcha" data-sitekey="6LeySRIUAAAAAJnYn_JKQ8i2UfH85wKA-YgSYACL"></div>
  4. To verify the user clicked to reCAPTCHA correctly, we need to make a request to Google. Below I use PHP, but the same request can be made to the URL using other programming languages.
    // build the request url
    $verify_url = 'https://www.google.com/recaptcha/api/siteverify';
    $args = array('secret' => '6LeySRIUAAAAAM5d8huz1-SIW4OMjfgDx_pwfToe',
                  'response' => $_POST['g-recaptcha-response'],
                  'remoteip' => $_SERVER['REMOTE_ADDR']);
    $request_url = $verify_url.'?'.http_build_query($args);
    
    // a JSON object is returned
    $response = file_get_contents($request_url);
    
    // decode the information
    $json = json_decode($response, true); // true decodes it to an array instead of a PHP object
    
    // handle the response
    if($recaptcha['success'] == 1) {
    	// run code on successful reCAPTCHA
    } else {
    	// run code on unsuccessful reCAPTCHA
    }

    The query to Google can further be simplified to a single line

    $json = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LeySRIUAAAAAM5d8huz1-SIW4OMjfgDx_pwfToe&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
  5. That’s it!
Matt Engelbregtsen

Matt Engelbregtsen

Technical Account Manager