Google captcha validation with server side




Create Captcha Credential here


HTML:


   
   <form id="registration" name="registration" action="#" method="POST">
        <input type="text" name="name" placeholder="Name" />
        <input type="email" name="email" placeholder="Email" />
        <input type="number" name="number" placeholder="Mobile Number" />
        <input type="password" name="password" placeholder="Password" />
        <div class="form-group">
            <div class="g-recaptcha" data-sitekey="6LcWrMQUAAAAAHbCcCs08zYuhGvdeO16D8WXL-Da" data-callback="verifyRecaptchaCallback" data-expired-callback="expiredRecaptchaCallback"></div>
            <input class="form-control d-none" require data-recaptcha="true" data-error="Please complete the Captcha">
            <div class="help-block with-errors"></div>
        </div>
        <input type="submit" name="submit" value="Register" />
    </form>




JS: 


        var IsCapchaFilled = false;


        // start window onload
        function verifyRecaptchaCallback(e) {
        var formData = new FormData(registration);
        formData.append("g-recaptcha-response"e)
        fetch('php/verify-captcha.php', {
        method: 'post',
        body: formData
        }).then(res => res.json())
        .then(res => {
        if (res.success) {
            IsCapchaFilled = true;
        }
        console.log(res);
        });
        }



        function expiredRecaptchaCallback(e) {
        fetch('php/destroy-captcha.php', {
        method: 'post',
        }).then(res => res.text())
        .then(res => {
        IsCapchaFilled = false;
        });
        }



        var registration = document.querySelector("#registration");

        registration.onsubmit = (e=> {
        e.preventDefault();
        //when form submit just checke IsCapchaFilled
        if (IsCapchaFilled) {
        // do your own code
        }
        else {
        // captcha not verified
        }

        }



PHP:
 inside: php/verify-captcha.php


        <?php 
        session_start();

        if ($_SERVER['REQUEST_METHOD'] == 'POST'){
        $captcha_response = $_POST['g-recaptcha-response'];
        $secretKey = "6LcWrMQUAAAAADdsdfsfdsdfUh1MfTGQtPUC7Vc4dbLVF";



        $url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha_response;

        $options = array(
        'http' => array(
        'header'  => "Content-type: application/json",
        'method'  => 'GET',

        )
        );

        $context  = stream_context_create($options);
        $result = file_get_contents($urlfalse$context);
        $_SESSION['rCaptcha'] = "true";
        echo $result;

        }

        ?>



Just check when form submit on serverside $_SESSION['rCaptcha']








Comments