Integration Google reCAPTCHA
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I have created reCAPTCHA API keys and I have Site key and Secret key.

I have made step 1: Client-side integration.

I need help with step 2: Server-side integration.

Server side should be integrated into the existing PHP code.
If someone does not confirm reCAPTCHA, warning must appear under reCAPTCHA div as like other fields. Form validation rules and message should be integrated into existing Javascript.

Testing link: http://www.copy-electronic.hr/recaptcha

Javascript /FORM/ validation: http://www.copy-electronic.hr/style/js/a/scripts.v1.0.4.js

PHP:

if( isset($_POST['name']) )
{
$to = 'web.prodaja@copy-electronic.hr';
$subject = 'Web upit - Copy Electronic';
$headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'];
$message = 'Ime: ' . $_POST['name'] . "\n" .
                    'E-pošta: ' . $_POST['email'] . "\n" .
                    'Naslov: ' . $_POST['subject'] . "\n" .
                    'Poruka: ' . $_POST['message'];
mail($to, $subject, $message, $headers);    
    if( $_POST['copy'] == 'on' )
    {
        mail($_POST['email'], $subject, $message, $headers);
    }
}
awarded to tomtoump
Tags
php
recaptcha

Crowdsource coding tasks.

3 Solutions


Make sure you copy all the recaptcha libraries to the recaptcha dir. You should also check if all the other variables are set.

require('recaptcha/autoload.php');

$secret = "your_secret_key";
$recaptcha = new \ReCaptcha\ReCaptcha($secret);

$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

if( isset($_POST['name']) && $resp->isSuccess()) {
    $to = 'web.prodaja@copy-electronic.hr';
    $subject = 'Web upit - Copy Electronic';
    $headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'];
    $message = 'Ime: ' . $_POST['name'] . "\n" .
                        'E-pošta: ' . $_POST['email'] . "\n" .
                        'Naslov: ' . $_POST['subject'] . "\n" .
                        'Poruka: ' . $_POST['message'];
    mail($to, $subject, $message, $headers);    
   if( $_POST['copy'] == 'on' ) {
    mail($_POST['email'], $subject, $message, $headers);
   }
}

Regarding javascript code, I can not fix that because I would have to have access to more code than you posted.


You need to update the existing HTML where the captcha is rendered to integrate the error message for the captcha.

HTML:

<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
<div class="g-recaptcha" data-sitekey="6LeevP4SAAAAAD7tnww8f3BRR228haSZl4jZBF15"></div>

Javascript with validation for captcha:

$(function() {
    // Validation
    $("#sky-form").validate({
        ignore: ".ignore",

        // Rules for form validation
        rules: {
            name: {
                required: true
            },
            email: {
                required: true,
                email: true
            },
            phone: {
                required: true
            },
            jmba: {
                required: true
            },
            date: {
                required: true
            },
            time: {
                required: true
            },
            subject: {
                required: true
            },
            message: {
                required: true
            },
            hiddenRecaptcha: {
                required: function() {
                    if(grecaptcha.getResponse() == '') {
                        return true;
                    } else {
                        return false;
                    }
                }
            }
        },
        // Messages for form validation
        messages: {
            name: {
                required: 'Upiši svoje ime',
            },
            email: {
                required: 'Upiši svoju e-poštu',
                email: 'Upiši ISPRAVNU e-poštu'
            },
            phone: {
                required: 'Upiši broja telefona da te tehnicar može kontaktirati u slucaju dodatnih pitanja',
            },
            jmba: {
                required: 'Upiši JMBA ili model uredaja da tehnicar zna o kojem se modelu radi',
            },
            date: {
                required: 'Odaberi datum kada želiš servis',
            },
            time: {
                required: 'Upiši radno vrijeme u koje tehnicar može doci',
            },
            subject: {
                required: 'Upiši naslov poruke',
            },
            message: {
                required: 'Upiši poruku'
            },
            hiddenRecaptcha: {
                required: 'You must complete the CAPTCHA'
            }
        },
        // Ajax form submition                  
        submitHandler: function(form) {
            $(form).ajaxSubmit({
                beforeSend: function() {
                    l.start();
                    $('#sky-form button[type="submit"]').attr('disabled', true);
                },
                success: function() {
                    l.stop();
                    $("#sky-form").addClass('submited');
                }
            });
        },
        // Do not change code below
        errorPlacement: function(error, element) {
            error.insertAfter(element.parent());
        }
    });
});

You can update the error message for the captcha above, like the other messages.

PHP:

require('/path/to/recaptcha/src/autoload.php');

$secret = ''; // your secret key here
$isCaptchaVerified = false;

if (isset($_POST['g-recaptcha-response'])) {
    $recaptcha = new \ReCaptcha\ReCaptcha($secret);
    $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

    if ($resp->isSuccess()) {
        $isCaptchaVerified = true;
    }
}

if( isset($_POST['name']) && $isCaptchaVerified)
{
$to = 'web.prodaja@copy-electronic.hr';
$subject = 'Web upit - Copy Electronic';
$headers = 'From: ' . $_POST['email'] . "\r\n" . 'Reply-To: ' . $_POST['email'];
$message = 'Ime: ' . $_POST['name'] . "\n" .
                    'E-pošta: ' . $_POST['email'] . "\n" .
                    'Naslov: ' . $_POST['subject'] . "\n" .
                    'Poruka: ' . $_POST['message'];
mail($to, $subject, $message, $headers);    
    if( $_POST['copy'] == 'on' )
    {
        mail($_POST['email'], $subject, $message, $headers);
    }
}

You need to use the reCAPTCHA PHP client library (and update the path to the autoload in the script above). You can download it from https://github.com/google/recaptcha

Don't forget to fill the secret key in the above PHP script.

Note: You should verify all your fields at server side (validate email, check message is plain text, etc.).

Let me know if you find any problems.

Edit 1: Updated Javascript validation. I had forgot to add a line to make the hidden field work.

Hi Nuno, for now, I like your idea seems quite good. But the form does not work. In PHP line 9 tells me some syntax error that I have to fix.
Saaskoo almost 4 years ago
Sorry, I had forgotten to include a line to make the hidden field work. I edited the Javascript solution now. Can you tell me which error you're seeing in PHP? Did you place the reCAPTCHA PHP client library in the correct path and did you update the "require" at the top of the PHP script from my solution?
Nuno Freitas almost 4 years ago
Hi Nuno, for best comparison, I've made your version that now works fantastically. Seems better for UX than disabled button. One more UX problem. When you first click on the SEND button, everywhere warning appears. Immediately upon entry into the field or clicking outside the field, the warning disappears.Can you make it so that the warning 'You must complete the CAPTCHA' removed when the user confirms? http://www.copy-electronic.hr/recaptcha-nuno
Saaskoo almost 4 years ago

You can download the code here.

Apart from checking the reCAPTCHA, I check every submitted variable because you should not rely only on JS. That's also the reason for doing the reCAPTCHA check on the server.

<?php

require('recaptcha/autoload.php');

/**
 * Configuration
 */
$secret = 'YOUR_SECRET';

if ( ! empty($_POST['name']) &&
     ! empty($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) &&
     ! empty($_POST['subject']) &&
     ! empty($_POST['message']) &&
     ! empty($_POST['g-recaptcha-response'])) {

    $recaptcha = new \ReCaptcha\ReCaptcha($secret);
    $response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

    if ($response->isSuccess()) {
        $to = 'web.prodaja@copy-electronic.hr';
        $subject = 'Web upit - Copy Electronic';
        $headers = 'From: ' . $_POST['email'] . "\r\n" .
                   'Reply-To: ' . $_POST['email'];
        $message = 'Ime: ' . $_POST['name'] . "\n" .
                   'E-pošta: ' . $_POST['email'] . "\n" .
                   'Naslov: ' . $_POST['subject'] . "\n" .
                   'Poruka: ' . $_POST['message'];

        mail($to, $subject, $message, $headers);

        if( $_POST['copy'] == 'on' ) {
            mail($_POST['email'], $subject, $message, $headers);
        }
    }
}

Set the data-callback attribute on this element:

<div class="g-recaptcha" data-sitekey="6LeevP4SAAAAAD7tnww8f3BRR228haSZl4jZBF15" data-callback="recaptchaSuccess"></div>

And replace/add this JS to your scripts file :

$(function() {
    // Validation
    $("#sky-form").validate({
        // Rules for form validation
        rules: {
            /*
             * ...
             */
            'g-recaptcha-response': {
                required: true
            }
        },
        // Messages for form validation
        messages: {
            /*
             * ...
             */
            'g-recaptcha-response': {
                required: 'YOUR_ERROR_MESSAGE'
            }
        },
        // submitHandler
        // errorPlacement
    });
});

function recaptchaSuccess(){
    $('#g-recaptcha-response').valid();
}
Hi Tom, for best compare, I made your version. Curently not working. After pressing the SEND button, nothing happens. http://www.copy-electronic.hr/recaptcha-tom
Saaskoo almost 4 years ago
Fixed. It should be OK now.
tomtoump almost 4 years ago
Also removes error message upon recaptcha challenge completion.
tomtoump almost 4 years ago
Hi Tom, now I receive message but on client side nothing happened. And warning for check CAPTCHA doesn't show up. http://www.copy-electronic.hr/recaptcha-tom
Saaskoo almost 4 years ago
It seems like you don't include the correct JS file. Please use this one.
tomtoump almost 4 years ago
Sorry for the back and forth, but it's quite difficult when you don't have direct access. Updated the JS in the previous comment because it contained an error.
tomtoump almost 4 years ago
Hm, now after click SEND button open blank PHP http://www.copy-electronic.hr/form-tom.php
Saaskoo almost 4 years ago
Now form works without checking reCaptcha. http://www.copy-electronic.hr/form-tom.php
Saaskoo almost 4 years ago
Now works like a charm :)
Saaskoo almost 4 years ago
Looks cool now :)
tomtoump almost 4 years ago
Yes! Now it only remains to see if google prevent spammers. Thanks again tomtoump for your help :)
Saaskoo almost 4 years ago
View Timeline