Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Google Recaptcha - PHP not executing

Tags:

php

recaptcha

I'm a PHP noob and I am trying to incorporate the new google recaptcha into a site. There is a form in the html doc that calls on a "sendemail.php" file (code below). The problem is that the form is working, regardless of whether or not the recaptcha done properly by the user. In my code, it will always execute "codeB", regardless of users' failure to complete the recaptcha.

What am I screwing up?

<?php
$captcha=$_POST['g-recaptcha-response'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=##########11&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
    //codeA that I want to execute if the recaptcha fails
    echo '<p>Please Go Back And Try Again</p>';
}
else
{
    //codeB that I want to execute upon success of the recaptcha
}
?>
like image 501
yefimovich Avatar asked Mar 03 '26 02:03

yefimovich


1 Answers

There's 2 mistakes with your code, first one is which someone above mentioned that you need to use json_decode. Second of all, you cannot check the value by adding .success infront of $response.

Here is the correct code which works:

$captchaSecretCode = 'placeYourSecretCodeHere';
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$captchaSecretCode."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']), true);

if($response['success'] == true)
{
    echo 'true';
}else{
    echo 'false';
}
like image 150
J. Doe Avatar answered Mar 04 '26 16:03

J. Doe