Monday, December 18, 2017

Simple Self-Contained RECAPTCHA Example

<!doctype html>
<html>
    <head>
        <title>Google reCAPTCHA demo</title>
        <script src='https://www.google.com/recaptcha/api.js'></script>
    </head>
    <body>
        <form method="post" action="recaptcha_test.php">
            <div class="g-recaptcha" data-sitekey="CHANGE THIS TO YOUR SITE KEY"></div>
            <input type="submit" />
        </form>
    </body>
</html>

<?php

    if($_SERVER["REQUEST_METHOD"] === "POST")
    {
        // Copy this (the html above too) to recaptcha_test.php (/tmp/recaptcha_test.php)   
        // cd to directory, start up php -S localhost:9000, 
        // then browse to http://localhost:9000/recaptcha_test.php
        
        //form submitted    

        //check if other form details are correct

        //verify captcha
        $recaptcha_secret = "CHANGE THIS TO YOUR SECRET KEY";
        $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
        $response = json_decode($response, true);
        if($response["success"] === true)
        {
            echo "Logged In Successfully";
        }
        else
        {
            echo "You are a robot";
        }
    }
?>

No comments:

Post a Comment