Verify a reCAPTCHA using PHP 8.3

Here’s a PHP 8.3 function to verify a reCAPTCHA response with Google’s server. Ensure you replace YOUR_SECRET_KEY with your actual reCAPTCHA secret key.

<?php
/**
 * Verifies a reCAPTCHA response with Google's server.
 *
 * @param string $recaptchaResponse The response token from the client-side reCAPTCHA.
 * @param string $secretKey The secret key for your reCAPTCHA account.
 *
 * @return bool True if verification is successful, otherwise false.
 */
function verifyRecaptcha(string $recaptchaResponse, string $secretKey): bool
{
    // Google reCAPTCHA verification endpoint
    $url = 'https://www.google.com/recaptcha/api/siteverify';

    // Prepare the POST data
    $postData = [
        'secret' => $secretKey,
        'response' => $recaptchaResponse
    ];

    // Initialize cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    // Execute the request
    $response = curl_exec($ch);
    curl_close($ch);

    // Decode the JSON response
    $responseData = json_decode($response, true);

    // Check if the verification was successful
    return $responseData['success'] ?? false;
}

// Example usage
$recaptchaResponse = $_POST['g-recaptcha-response'] ?? '';
$secretKey = 'YOUR_SECRET_KEY';

if (verifyRecaptcha($recaptchaResponse, $secretKey)) {
    echo 'reCAPTCHA verification successful.';
} else {
    echo 'reCAPTCHA verification failed.';
}

Explanation:

  1. Endpoint: The function uses the https://www.google.com/recaptcha/api/siteverify endpoint for verification.
  2. Input: The function accepts the reCAPTCHA response from the client and your secret key.
  3. cURL: The function sends a POST request to Google’s server with the necessary parameters (secret and response).
  4. Response Handling: The response is decoded from JSON and checked for the success field.
  5. Security: The secret key should never be exposed to the client-side. Ensure it is stored securely on the server.

Notes:

  • Make sure the cURL extension is enabled in your PHP installation.
  • If you’re using a framework, consider using its HTTP client instead of cURL for better maintainability.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *