What are some best practices for handling form validation and error messages in PHP when submitting a form, especially with Google reCAPTCHA integration?

When submitting a form in PHP, it is essential to perform proper validation on the input data to ensure data integrity and security. Additionally, integrating Google reCAPTCHA can help prevent spam submissions. To handle form validation and error messages effectively, you can check for errors after form submission, display appropriate error messages, and prevent the form from being processed until all validation checks pass.

<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form fields
    $name = $_POST['name'];
    $email = $_POST['email'];
    
    // Perform validation checks
    $errors = [];
    
    if (empty($name)) {
        $errors[] = "Name is required";
    }
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    
    // Check Google reCAPTCHA
    $recaptcha_secret = 'YOUR_RECAPTCHA_SECRET_KEY';
    $recaptcha_response = $_POST['g-recaptcha-response'];
    $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify?secret='.$recaptcha_secret.'&response='.$recaptcha_response;
    $recaptcha_data = json_decode(file_get_contents($recaptcha_url));
    
    if (!$recaptcha_data->success) {
        $errors[] = "reCAPTCHA verification failed";
    }
    
    // Display error messages
    if (!empty($errors)) {
        foreach ($errors as $error) {
            echo $error . "<br>";
        }
    } else {
        // Process the form data
        // Insert data into database, send email, etc.
    }
}
?>