-1

I have a form which I'm trying to use Recaptcha on.

I finally wound up just going with this one, which looked almost exactly as my form and PHP files did originally (so that seemed easy enough). Unfortunately, whether Recaptcha checkbox is clicked or not, the "Please check the recaptcha box" error pops up, indicating that it isn't working.

Here is the HTML:

     <form class="contact__form" method="post" action="mail.php">
                                
                                <!-- form message -->
                                <div class="row">
                                    <div class="col-12">
                                        <div class="contact__msg" style="display: none">
                                            <p>Your message was sent successfully.</p>
                                        </div>
                                    </div>
                                </div>
                                <!-- end message -->

                                <!-- form element -->
                                <div class="row">
                                    <div class="col-md-6 form-group">
                                        <input name="name" type="text" class="form-control" placeholder="Name" required>
                                    </div>
                                    <div class="col-md-6 form-group">
                                        <input name="email" type="email" class="form-control" placeholder="Email" required>
                                    </div>
                                    <div class="col-md-6 form-group">
                                        <input name="phone" type="text" class="form-control" placeholder="Phone" required>
                                    </div>
                                    <div class="col-12 form-group">
                                        <textarea name="message" class="form-control" rows="3" placeholder="Message" required></textarea>
                                    </div>
                                    <div class="col-12 form-group">
                                        <div class="g-recaptcha" data-sitekey="6LfrrScdAAAAAM9UdXgQL4bHsISIEtYKW3Yca2Xm"></div>
                                    </div>
                                    <div class="col-12">
                                        <input name="submit" type="submit" class="btn btn-success" value="Send Message">
                                    </div>
                                </div>
                                <!-- end form element -->
                            </form>

PHP:

<?php

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

        // access
        $secretKey = '....';
        $captcha = $_POST['g-recaptcha-response'];

        if(!$captcha){
          echo 'Please check the captcha form';
          exit;
        }

        # FIX: Replace this email with recipient email
        $mail_to = "[email protected]";
        
        # Sender Data
        $subject = "...";
        $name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST["name"])));
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $phone = trim($_POST["phone"]);
        $message = trim($_POST["message"]);
        
        if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL) OR empty($phone) OR empty($subject) OR empty($message)) {
            # Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo 'Please complete the form and try again';
            exit;
        }

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

        if(intval($responseKeys["success"]) !== 1) {
          echo 'Please check the the captcha form.';
        } else {
            # Mail Content
            $content = "Name: $name\n";
            $content .= "Email: $email\n\n";
            $content .= "Phone: $phone\n";
            $content .= "Message:\n$message\n";

            # email headers.
            $headers = "From: $name <$email>";

            # Send the email.
            $success = mail($mail_to, $subject, $content, $headers);
            if ($success) {
                # Set a 200 (okay) response code.
                http_response_code(200);
                echo 'Thank You! Your message has been sent';
            } else {
                # Set a 500 (internal server error) response code.
                http_response_code(500);
                echo 'Oops! Something went wrong, we couldnt send your message';
            }
        }

    } else {
        # Not a POST request, set a 403 (forbidden) response code.
        http_response_code(403);
        echo 'There was a problem with your submission, please try again.';
    }

?>

And finally, the JS file which is being called in the HTML file with the form:

(function ($) {
    'use strict';

    var form = $('.contact__form'),
        message = $('.contact__msg'),
        form_data;

    // Success function
    function done_func(response) {
        message.fadeIn()
        message.html(response);
        setTimeout(function () {
            message.fadeOut();
        }, 5000);
        
        form.find('input:not([type="submit"]), textarea').val('');
    }

    // fail function
    function fail_func(data) {
        message.fadeIn()
        message.html(data.responseText);
        setTimeout(function () {
            message.fadeOut(5000);
        }, 5000);
    }
    
    form.submit(function (e) {
        e.preventDefault();
        form_data = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: form.attr('action'),
            data: form_data
        })
        .done(done_func)
        .fail(fail_func);
    });
})(jQuery);
4
  • I can't even get my code to post here using the instructions (it misses a chunk of it every time and the PHP won't output correctly at all), - i don't buy it, just put the code under 3x apostrophe and end the code with 3x - if that fails, record a video of you doing it and it failing and upload it on youtube or something
    – hanshenrik
    Commented May 5, 2022 at 23:41
  • I did precisely that, and I assure you it came out looking like gibberish. I also used the Control-K, 4 line breaks, etc. Edit - good lord, I was misreading that as an apostraphe instead of... whatrever it actually is. Post edited Commented May 5, 2022 at 23:48
  • It's called a backtick. Used heavily in javascript and PHP, both of which you are using, so good to know where it gets applied. Why are you trying to hack up your own solution to this rather than using the PHP client library from google? github.com/google/recaptcha
    – gview
    Commented May 6, 2022 at 0:09
  • I'm not a web developer. I look at github pages and don't even know what I'm reading. I've actually perused that page but I don't see any example functions for how it's commonly recommended to verify the captcha and then go ahead with sending the email. Commented May 6, 2022 at 0:17

1 Answer 1

0

that API want POST data, not GET data. for example with hhb_curl i use i've like

        $captcha_response = (new hhb_curl ( 'https://www.google.com/recaptcha/api/siteverify', true ))->setopt_array ( array (
                CURLOPT_POSTFIELDS => array (
                        'secret' => '...',
                        'response' => $_POST ['g-recaptcha-response'],
                        'remoteip' => $ip 
                ) 
        ) )->exec ()->getResponseBody ();
        $captcha_response = json_decode ( $captcha_response, true , 999, JSON_THROW_ON_ERROR);
        if($captcha_response ['success'] !== true) {
            http_response_code ( 400 );
            header ( "content-type: text/plain;charset=utf8" );
            die ( 'reCaptcha error!: ' . hhb_return_var_dump ( $captcha_response  ) );
        }

Not the answer you're looking for? Browse other questions tagged or ask your own question.