How can PHP be used to retain form data when validation errors occur?

When validation errors occur in a form submission, PHP can retain the form data by storing it in session variables and then repopulating the form fields with this data. This allows users to correct their errors without having to re-enter all the information.

<?php
session_start();

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form data
    // If validation fails, store form data in session
    $_SESSION['form_data'] = $_POST;
    // Redirect back to the form page
    header("Location: form_page.php");
    exit;
}

// Repopulate form fields with session data
if(isset($_SESSION['form_data'])) {
    $form_data = $_SESSION['form_data'];
    unset($_SESSION['form_data']);
}

?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="text" name="name" value="<?php echo isset($form_data['name']) ? $form_data['name'] : ''; ?>">
    <input type="email" name="email" value="<?php echo isset($form_data['email']) ? $form_data['email'] : ''; ?>">
    <button type="submit">Submit</button>
</form>