PHP Google reCAPTCHA v2

Posted on October 25, 2017 at 9:59 am

First you need to create the Google reCAPTCHA v2 key for your website.

This is the HTML form example that shows the reCAPTCHA:

* Replace YOUR_SITE_KEY_HERE with your site key *

<form action="" method="post">
    <div class="form-group" style="max-width: 303px;">
        <input type="email" name="email" placeholder="Enter email here..." class="form-control" required email>
    </div>
    <div class="form-group">
        <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY_HERE"></div>
    </div>
    <button type="submit" name="go" class="btn btn-success">Subscribe Now</button>
</form>

And this is the example PHP code:

* Replace YOUR_SECRET_KEY_HERE with your secret key *

if ( isset($_POST['email']) )
{
    if(isset($_POST["g-recaptcha-response"]) && $_POST["g-recaptcha-response"] != "")
    {
        $verify = curl_download_url("https://www.google.com/recaptcha/api/siteverify?secret=YOUR_SECRET_KEY_HERE&response=".$_POST["g-recaptcha-response"]);
 
        $captcha_success=json_decode($verify);
 
        if ($captcha_success->success==false)
        {
            echo '<p class="alert alert-danger">Wrong captcha, try again.</p>';
        }
        else if ($captcha_success->success==true)
        {
            // CAPTCHA IS OK :)
            // WRITE YOUR CODE HERE...
        }
    }
    else
    {
        echo '<p class="alert alert-danger">Wrong captcha, try again.</p>';
    }
}

And this is the function curl_download_url():

function curl_download_url( $url )
{
    $curl = curl_init();
    curl_setopt ($curl, CURLOPT_URL, $url);
    curl_setopt ($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1");
    curl_setopt ($curl, CURLOPT_HEADER, 0);
    curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, false);
    $html = curl_exec ($curl);
    curl_close ($curl);
    return $html;
}

Other Posts

Updated Posts