A Guide to Installing reCAPTCHA in a PHP Form

Table of contents

No heading

No headings in the article.

reCAPTCHA is a widely used service to protect your website from spam and abuse. In this tutorial, we'll walk you through the process of installing reCAPTCHA in a PHP form. To keep things simple and safe, we'll use dummy keys for this example.

Prerequisites:

  • A basic understanding of HTML, PHP, and web development.

  • Access to a web server for hosting your PHP code.

Step 1: Create a reCAPTCHA Account

  • Visit the reCAPTCHA website and sign in with your Google account.

  • Click on "Admin Console" to create a new reCAPTCHA site.

  • Fill in the required information:

    • Label: A name for your reCAPTCHA site.

    • reCAPTCHA Type: Select "reCAPTCHA v2" and then "I'm not a robot" Checkbox.

    • Domains: Add your domain where you'll use reCAPTCHA. For testing, you can use "localhost."

  • Accept the reCAPTCHA Terms of Service and click "Submit."

  • Once submitted, you'll see the "Site Key" and "Secret Key." We will use these keys in our PHP form.

Step 2: Implement reCAPTCHA in Your PHP Form

Now, let's integrate reCAPTCHA into your PHP form using the provided code with dummy keys. add this javascript code to the head section of your website. <script src="google.com/recaptcha/api.js" async defer></script>

<?php


$captcha_error = '';

// Processing form data when the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST['g-recaptcha-response'])) {
        $captcha_error = 'reCAPTCHA verification failed. Please check the reCAPTCHA box.'; // Error message for empty reCAPTCHA
    } else {



        // Google secret API
        $secretAPIkey = '6LdryIsoAAAAAKcoDHadhsjhdsdksgdshdjssdjsj';

        // Create a cURL handle
        $ch = curl_init();

        // Set cURL options
        curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'secret' => $secretAPIkey,
            'response' => $_POST['g-recaptcha-response']
        ]));

        // Execute the cURL request
        $verifyResponse = curl_exec($ch);

        // Close the cURL handle
        curl_close($ch);

        if ($verifyResponse) {
            $response = json_decode($verifyResponse);
            if (!$response->success) {
                $captcha_error = 'reCAPTCHA verification failed. Please try again.'; // Custom error message
            } else {
                $captcha_error = 'reCAPTCHA verification successful.';
            }
        } else {
            $captcha_error = 'cURL request failed';
        }
    }
}
?>

<html>

<head>
  <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<!-- Add the reCAPTCHA widget to your form -->
<form action="signup.php" method="post">
    <div class="g-recaptcha" data-sitekey="6LSDHhddsjsdbajafjafhjfjafb"></div>
    <button type="submit" value="Submit">Sign Up</button>
    <span class="help-block" style="color:red;font-size:12px;"><?php echo $captcha_error; ?></span>
</form>
</body>
</html>

In this code, replace $dummySiteKey with your actual Site Key obtained from the reCAPTCHA admin console.

Step 3: Testing and Deployment

  • Test your form with reCAPTCHA on a local server or staging environment to ensure it's working as expected.

  • Deploy your PHP form to your live website.

With reCAPTCHA integrated into your PHP form, you'll be able to protect your website from spam and abuse while ensuring a smooth user experience.