What are the different methods available in PHP to store and retrieve data from HTML forms without losing existing data?

When submitting an HTML form in PHP, it is important to ensure that existing data entered by the user is not lost when the form is reloaded. One common method to achieve this is by using PHP sessions to store form data and then retrieve it when the form is reloaded. Another approach is to use hidden input fields in the form to store the data temporarily. Both methods allow for seamless user experience and prevent data loss.

<?php
session_start();

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Store form data in session
    $_SESSION['form_data'] = $_POST;
    // Redirect to prevent form resubmission
    header("Location: {$_SERVER['REQUEST_URI']}");
    exit;
}

// Retrieve form data from session
$form_data = isset($_SESSION['form_data']) ? $_SESSION['form_data'] : [];

// Clear form data from session
unset($_SESSION['form_data']);
?>

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