What are some best practices for maintaining user selections in PHP forms?

When users submit a form in PHP, it's important to maintain their selections if there are any errors in the form submission. This can be achieved by storing the user's input in session variables and repopulating the form fields with those values when the form is displayed again.

// Start the session
session_start();

// Check if form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Store user input in session variables
    $_SESSION['username'] = $_POST['username'];
    $_SESSION['email'] = $_POST['email'];
    // Add more session variables for other form fields as needed
}

// Display the form with user selections
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    Username: <input type="text" name="username" value="<?php echo isset($_SESSION['username']) ? $_SESSION['username'] : ''; ?>"><br>
    Email: <input type="email" name="email" value="<?php echo isset($_SESSION['email']) ? $_SESSION['email'] : ''; ?>"><br>
    <!-- Add more form fields with their corresponding session variables -->
    <input type="submit" value="Submit">
</form>

// Clear session variables after form submission
unset($_SESSION['username']);
unset($_SESSION['email']);
// Add more unset statements for other session variables used in the form