Igor Simic
7 years ago

How to use Google reCAPTCHA with PHP


Google reCAPTCHA is a good way to stop spammers on your web site, and it will prevent "non humans" to register on your form.

So how does Google reCAPTCHA works:

Ffirst you have to include reCAPTCHA JS and add recaptcha element to your form:
<script src="https://www.google.com/recaptcha/api.js?hl=<?php echo $lang; ?>" async defer></script>

<!-- simple form with recaptcha included -->
	<form action="" method="POST">
	    <input type="text" name="name" value="name" />
	    <input type="text" name="email" value="email" />
	    <textarea type="text" name="message">Message .....</textarea>
	    <div class="g-recaptcha" data-sitekey="YOUR SITE KEY"></div>
	    <input type="submit" name="submit" value="SUBMIT">
	</form>
As you can see wee are adding language parameter to recaptcha JS which can be defined in your PHP file:
$lang = 'en';
To see all  supported languages and the country codes you can visit this link:
https://developers.google.com/recaptcha/docs/language

Also we have to include data site key which can be created on Google recaptcha site:
https://www.google.com/recaptcha/admin#list

For testing purposes you can also create local domain in your apache virtual hosts and add that domain into your recaptcha website list, for example:
loc.dev

When form is submitted we need to check do we have posted value from recaptcha in g-recaptcha-response and then validate it with another call to Google services:

if(isset($_POST['submit']) && !empty($_POST['submit'])){ 

	// check do we have recaptcha param added to form and submited
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){ 
        
        //your site secret recaptcha key
        $secret = 'YOUR-SITE-SECRET-RECAPTCHA-KEY';
 
         
        //get verify response data
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        
        $responseData = json_decode($verifyResponse); 
        
        // check was the response successfully checked by Google
        if($responseData->success){
          	// if recaptcha check was success
            $succMsg = 'Your contact request have submitted successfully.';
            exit($succMsg); 
        }else{
        	// if not show the error
            $errMsg = 'Robot verification failed, please try again.';
            echo $errMsg;
 
        }
         
    }else{
    	// if recaptcha is not checked
        $errMsg = 'Please click on the reCAPTCHA box.';
    } 
} 

And if everything is good you can  submit your form to DB, but of course you have to sanitize  and validate other data submitted from the form.

So the complete very simple example page with Google reCAPTCHA can look like  this:
 <?php

// when form is sibmitted

if(isset($_POST['submit']) && !empty($_POST['submit'])){ 

	// check do we have recaptcha param added to form and submited
    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){ 
        
        //your site secret recaptcha key
        $secret = 'YOUR-SITE-SECRET-RECAPTCHA-KEY';
 
         
        //get verify response data
        $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
        
        $responseData = json_decode($verifyResponse);
 
     	// check was the response successfully checked by Google
        if($responseData->success){
          	// if recaptcha check was success
            $succMsg = 'Your contact request have submitted successfully.';
            exit($succMsg); 
        }else{
        	// if not show the error
            $errMsg = 'Robot verification failed, please try again.';
            echo $errMsg;
 
        }
         
    }else{
    	// if recaptcha is not checked
        $errMsg = 'Please click on the reCAPTCHA box.';
    } 
} 
// set language for recaptcha
$lang = 'en';

?> 
<html>

<!-- include recaptcha JS -->	
<script src="https://www.google.com/recaptcha/api.js?hl=<?php echo $lang; ?>" async defer></script>
<body>
	
	<!-- simple form with recaptcha included -->
	<form action="" method="POST">
	    <input type="text" name="name" value="name" />
	    <input type="text" name="email" value="email" />
	    <textarea type="text" name="message">Message .....</textarea>
	    <div class="g-recaptcha" data-sitekey="YOUR SITE KEY"></div>
	    <input type="submit" name="submit" value="SUBMIT">
	</form>
 

</body>
 
</html>


More info you can find on official Google reCAPTCHA page!