How can server-side validation be implemented to retain user input data in PHP forms, especially when additional form elements are dynamically generated?

When using server-side validation in PHP forms with dynamically generated form elements, it is important to retain user input data to provide a seamless user experience. This can be achieved by storing the user input data in session variables and repopulating the form fields with the stored data if validation fails. By doing this, users do not lose their input when the form is submitted and errors are displayed.

<?php
session_start();

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form data
    // If validation fails
    if (/* validation fails */) {
        // Store user input data in session variables
        $_SESSION['input_data'] = $_POST;
        // Redirect back to the form page
        header("Location: form.php");
        exit();
    } else {
        // Clear stored user input data
        unset($_SESSION['input_data']);
        // Process form data
    }
}

// Repopulate form fields with stored input data
$input_data = isset($_SESSION['input_data']) ? $_SESSION['input_data'] : [];
?>

<form method="post" action="form.php">
    <input type="text" name="username" value="<?php echo isset($input_data['username']) ? $input_data['username'] : ''; ?>" />
    <input type="email" name="email" value="<?php echo isset($input_data['email']) ? $input_data['email'] : ''; ?>" />
    <!-- Add more form fields here -->
    <button type="submit">Submit</button>
</form>