How can PHP be used to redirect back to a form with user input intact after validation errors occur?

When validation errors occur in a form submission, you can use PHP to redirect back to the form page with the user input intact. To achieve this, you can store the user input in session variables before redirecting and then retrieve and populate the form fields with the session data when rendering the form again.

<?php
session_start();

// Validate form data
$errors = validateFormData($_POST);

if (empty($errors)) {
    // Process form data
    // Redirect to success page
    header("Location: success.php");
    exit();
} else {
    // Store user input in session
    $_SESSION['formData'] = $_POST;
    
    // Redirect back to form page
    header("Location: form.php");
    exit();
}

function validateFormData($data) {
    // Validation logic
    // Return array of errors
}
?>