How can the PHP header function be used effectively to redirect users with error messages in PHP forms?

When handling form submissions in PHP, it is common to redirect users after processing the form data. If there are errors detected during form validation, we can use the PHP header function to redirect users back to the form page with an error message displayed. By passing the error message as a query parameter in the URL, we can then retrieve and display it on the form page.

// Check for form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form data
    if (/* validation fails */) {
        // Redirect back to form page with error message
        header("Location: form.php?error=Please fill out all required fields");
        exit();
    } else {
        // Process form data
        // Redirect to success page
        header("Location: success.php");
        exit();
    }
}