Struggling with recaptcha v2 and form submission

millsteedo picture millsteedo · Dec 3, 2014 · Viewed 35.9k times · Source

https://developers.google.com/recaptcha/docs/verify

if(isset($_POST['submit'])){
$recaptchaResponse = $_POST['g-recaptcha-response'];
$secretKey = 'MYKEY';
$request = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$recaptchaResponse);

    if(!strstr($request,"false")){
echo '<div class="notification error clearfix"><p><strong>Attention!</strong> You didnt complete the captcha.</p></div>';
exit();

Then the rest of the php file mails the form, but its just sending anyway even if you dont complete the recaptcha. Basically if the JSON returns a false I was hoping the it wouldnt send and would display an error

Also here is the form from the page if it helps, Ive probably done something wrong there too...

<form method="POST" action="post.php" name="contactform" id="contactform" class="container">

            <fieldset>
                <div class="form-field grid-half">
                    <label for="name">Name</label>
                    <span><input type="text" name="name" id="name" /></span>
                </div>
                <div class="form-field grid-half">
                    <label for="email">Email</label>
                    <span><input type="email" name="email" id="email" /></span>
                </div>
                <div class="form-field grid-full">
                    <label for="message">Message</label>
                    <span><textarea name="message" id="message"></textarea></span>
                </div>                  
                <div class="form-field grid-full">
                        <div class="g-recaptcha" data-sitekey="MYKEY"></div>
                </div>
            </fieldset>
            <div class="form-click grid-full">
                <span><input type="submit" name="submit" value="Submit" id="submit" /></span>
            </div>

            <div id="alert" class="grid-full"></div>
        </form>     

Answer

Alan Kael Ball picture Alan Kael Ball · Jan 8, 2016

I found that sometimes, depending on the PHP version/config, accessing an object directly won't work, so use json_decode().

/* $response object returned from https://www.google.com/recaptcha/api/siteverify via which ever method you use */

$obj = json_decode($response);
if($obj->success == true)
{
    //passes test
}
else
{
    //error handling
}