How can session variables be effectively used to store and display error messages in PHP forms for a better user experience and data validation process?

When submitting a form in PHP, it is common practice to validate the user input and display error messages if any fields are incorrect. Using session variables to store these error messages allows for better user experience by persisting the errors across page reloads. By checking for these session variables in the form fields, we can display the errors next to the corresponding input fields.

<?php
session_start();

// Validate form data
if(empty($_POST['username'])) {
    $_SESSION['error_username'] = 'Username is required';
}

// Display form with error messages
?>

<form method="post" action="process_form.php">
    <input type="text" name="username" value="<?php echo isset($_POST['username']) ? $_POST['username'] : ''; ?>" />
    <?php if(isset($_SESSION['error_username'])) {
        echo '<span style="color: red;">' . $_SESSION['error_username'] . '</span>';
        unset($_SESSION['error_username']);
    } ?>
    
    <input type="submit" value="Submit" />
</form>