Thursday, December 18, 2014

Simple No Captcha reCaptcha implementation with PHP

Using new "No Captcha ReCaptcha" is quite simple. Below is a working example done in a single PHP page.

You can get ReCaptcha keys here:
https://www.google.com/recaptcha/intro/index.html

ReCaptcha secret key: Use this for communication between your site and Google. Be sure to keep it a secret.

ReCaptcha site key: Use this in the HTML code your site serves to users.

All you need to get this working is to edit values of $secret_key and data-sitekey. Just enter your values and it should work even in localhost. I believe that code is self-explanatory:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>No Captcha ReCaptcha</title>
    </head>
    <body>
        <?php
        // Get submited data.
        $g_recaptcha_response = filter_input(INPUT_POST, 'g-recaptcha-response');
        $msg = filter_input(INPUT_POST, 'msg');
        // Check if set.
        if (isset($g_recaptcha_response)) {
            // Your secret key.
            $secret_key = 'your-secret-key';
            $google = 'https://www.google.com/recaptcha/api/siteverify?secret='
                    . $secret_key . '&response=' . $g_recaptcha_response;
            // Get JSON response.
            $google_json = file_get_contents($google);
            $google_data = json_decode($google_json, true);
            if ($google_data['success']) {
                echo 'Hello human, this is your message: ' . $msg;
            } else {
                echo 'Robot detected! Error codes: ';
                print_r($google_data['error-codes']);
            }
            echo '<hr />';
        }
        ?>
        <form method="post">
            Your message: <input type="text" name="msg" />
            <script src='https://www.google.com/recaptcha/api.js'></script>
            <div class="g-recaptcha" 
                 data-sitekey="6Lcvq8gSAAAAABTXeNtu2TSUKDeL90VqBODLcc2b">
            </div>
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

I also made authentication library using "No Captcha" so check it out here: http://zoran87.blogspot.com/2014/12/zorauth-10b-complete-flexible-no.html

No comments:

Post a Comment