Search code examples
phpformsvalidationrecaptcha

PHP - Validate the recaptcha v2 response


#form.php

if(isset($_POST['g-recaptcha-response'])){
    $captcha=$_POST['g-recaptcha-response'];
    $captcha=$_GET["g-recaptcha-response"];
    $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=__1234__&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);

    echo $response;

Returns:

Notice: Undefined index: g-recaptcha-response in /var/www/clients/qmax/app/controllers/job_application_controller.php on line 114 { "success": false, "error-codes": [ "missing-input-response" ] }

echo $response->success;

Returns:

Notice: Trying to get property of non-object in /var/www/clients/qmax/app/controllers/job_application_controller.php on line 119

I just need to get the "success" object, then I can test if it is True OR False and I am done.


Solution

  • Remove this line:

    $captcha = $_GET["g-recaptcha-response"];
    

    Then you need to decode the json by Google like so:

    $g_response = json_decode($response);
    

    Then just check with if/else:

    if ($g_response->success === true) echo "success!";