Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google reCAPTCHA g-recpatcha-response has no value in PHP

p.s: I gave up on this as I found no solution and implemented my own php captcha that worked a treat :) - http://www.the-art-of-web.com/php/captcha/

I have spent many hours & days trying to solve this problem but I cannot seem to figure it out. I have read a lot of different tutorials & questions online.

Just to keep in mind, my PHP level is fairly basic.

I cannot seem to get the 'g-recaptcha-response' $_POST value in my php file.

I have summarised the important code needed below...

File 1: contact.php

Before Head Tags

<?php 
session_start(); // start php session

// Setup session variables to save the form data
if( isset($_SESSION['contact_form_values']) ){
    extract( $_SESSION['contact_form_values'] );
}

include('contactengine.php');
?>

In Head Tags

<script src='https://www.google.com/recaptcha/api.js'></script><!-- reCAPTCHA form -->

Between the Form tags Action="" so that it posts to itself which has the contactengine.php file included so that it runs through only when the user clicks the submit button?

<form class="contactform" method="POST" action="">

<div class="g-recaptcha" data-sitekey="6Lc92gkTAAAAAFKjZEOlY0cg9G8ubmlVoC13Xf3T"></div>

File 2: contactengine.php

Between this

if($_SERVER["REQUEST_METHOD"] == "POST")

I have

if( isset( $_POST['g-recaptcha-response'] ) ){
        $captchaResponse = $_POST['g-recaptcha-response'];
    }

Now this is the point where the variable $captchaResponse isn't being populated as I output the value of it like this:

if( !$captchaResponse ){ // check the POST recaptcha response value
        $resultMsg = 'Please check the captcha form. - '.$captchaResponse;
    }

Therefore I get no visible output of the response code in the $resultMsg string.

The only thing I could think is effecting it, is including the contactengine.php file at the beginning in contact.php. And having the action as ="". But this is what the tutorial guided me to do. So maybe not...

I used http://www.9lessons.info/2014/12/google-new-recaptcha-using-php-are-you.html as the guide.

Thanks a lot in advanced!

like image 386
Sam Bruton Avatar asked Oct 30 '22 23:10

Sam Bruton


1 Answers

You're nearly there! You just need to query Google's API.

if (isset($_POST['g-recaptcha-response'])) {
    $captcha = $_POST['g-recaptcha-response'];
}

if (!$captcha) {
    // Captcha wasn't checked, do something...
    exit;
}

$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=SECRETKEYGOESHERE&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);

if ($response.success == false) {
    // Captcha failed! Do something!
} else {
    // Captcha is valid! Do something else!
}

Replace SECRETKEYGOESHERE with your actual secret key, and you're set!

like image 193
Qirel Avatar answered Nov 04 '22 09:11

Qirel