What are best practices for error reporting and handling in PHP when dealing with ReCaptcha validation?

When dealing with ReCaptcha validation in PHP, it is important to properly handle any errors that may occur during the validation process. Best practices include checking for errors returned by the ReCaptcha API and displaying informative error messages to the user if validation fails.

// Perform ReCaptcha validation
$response = $_POST['g-recaptcha-response'];
$secretKey = 'YOUR_SECRET_KEY';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    'secret' => $secretKey,
    'response' => $response
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch), true);
curl_close($ch);

if (!$result['success']) {
    // ReCaptcha validation failed
    $errors = $result['error-codes'];
    foreach ($errors as $error) {
        echo 'ReCaptcha error: ' . $error;
    }
} else {
    // ReCaptcha validation successful
    echo 'ReCaptcha validation successful';
}