What are the best practices for implementing reCAPTCHA in PHP to prevent spam effectively?

To prevent spam effectively, implementing reCAPTCHA in PHP is a recommended solution. reCAPTCHA helps verify that a user is a human and not a bot, reducing the likelihood of spam submissions on forms or websites.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $recaptcha_secret = "YOUR_RECAPTCHA_SECRET_KEY";
    $recaptcha_response = $_POST["g-recaptcha-response"];
    $url = "https://www.google.com/recaptcha/api/siteverify?secret=$recaptcha_secret&response=$recaptcha_response";
    $response = file_get_contents($url);
    $responseKeys = json_decode($response, true);
    
    if(intval($responseKeys["success"]) !== 1) {
        // reCAPTCHA verification failed, handle accordingly
    } else {
        // reCAPTCHA verification successful, proceed with form submission
    }
}
?>