How can session variables be effectively passed to form fields in PHP?

When passing session variables to form fields in PHP, you can simply echo the session variable value as the default value for the form field. This way, the session variable will be displayed in the form field when the page loads.

<?php
session_start();

// Set session variable
$_SESSION['username'] = 'JohnDoe';

// Retrieve session variable and pass it to form field
$username = isset($_SESSION['username']) ? $_SESSION['username'] : '';

?>

<form action="submit.php" method="post">
    <input type="text" name="username" value="<?php echo $username; ?>">
    <button type="submit">Submit</button>
</form>