|

|  How to Implement CAPTCHA Using Google reCAPTCHA API in PHP

How to Implement CAPTCHA Using Google reCAPTCHA API in PHP

October 31, 2024

Learn how to integrate Google's reCAPTCHA API in PHP to secure your site, prevent bots, and enhance user experience with our step-by-step guide.

How to Implement CAPTCHA Using Google reCAPTCHA API in PHP

 

Integrate Google reCAPTCHA in PHP

 

To successfully integrate Google reCAPTCHA into your PHP application, it's important to execute the necessary backend validation to ensure security and proper functionality. Below are steps to guide you through the process.

 

Include reCAPTCHA JavaScript

 

Place the reCAPTCHA script inside the <head> section of your HTML file. The reCAPTCHA widget should be added to your form.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>reCAPTCHA Demo</title>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
    <form action="submit.php" method="POST">
        <!-- Your form fields here -->
        <div class="g-recaptcha" data-sitekey="your-site-key"></div>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

 

Handle Form Submission in PHP

 

Upon form submission, the reCAPTCHA widget returns a token. This token needs to be verified on the server-side to ensure it’s valid. Gather the token from POST data for validation.

 

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $recaptcha_secret = 'your-secret-key';
    $recaptcha_response = $_POST['g-recaptcha-response'];
    
    // Verify the reCAPTCHA response
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $data = [
        'secret' => $recaptcha_secret,
        'response' => $recaptcha_response
    ];
    
    $options = [
        'http' => [
            'method'  => 'POST',
            'content' => http_build_query($data)
        ]
    ];
    $context  = stream_context_create($options);
    $verify = file_get_contents($url, false, $context);
    $captcha_success = json_decode($verify);
    
    if ($captcha_success->success) {
        // Proceed with form handling
        echo "CAPTCHA verified successfully!";
    } else {
        // Handle invalid CAPTCHA
        echo "Error verifying CAPTCHA. Please try again.";
    }
}

 

Explanation of the PHP Code

 

  • The first check ensures that the form submission is done via the POST method to enhance security.
  • Use the `file_get_contents` function with a configured `stream_context` to make a POST request to Google’s reCAPTCHA API.
  • The verification response is a JSON object, which should be decoded to check the `success` property.
  • Proceed only if `success` is `true`. Otherwise, resend the form or display an error message to users.

 

Testing and Debugging

 

  • It's crucial to test the reCAPTCHA on both desktop and mobile devices since the interaction might differ slightly.
  • Verify network requests using browser developer tools to ensure that the token is sent and received correctly.

 

Understanding and properly implementing Google reCAPTCHA on the server-side helps in significantly reducing spam and automated submissions in web applications, thereby securing user data and resources.

Limited Beta: Claim Your Dev Kit and Start Building Today

Instant transcription

Access hundreds of community apps

Sync seamlessly on iOS & Android

Order Now

Turn Ideas Into Apps & Earn Big

Build apps for the AI wearable revolution, tap into a $100K+ bounty pool, and get noticed by top companies. Whether for fun or productivity, create unique use cases, integrate with real-time transcription, and join a thriving dev community.

Get Developer Kit Now