What potential pitfalls should be avoided when setting and accessing session variables in PHP?

Potential pitfalls when setting and accessing session variables in PHP include not initializing the session, not checking if the session variable exists before accessing it, and not properly sanitizing input data before storing it in session variables. To avoid these pitfalls, always start the session at the beginning of your PHP script, check if the session variable exists before accessing it, and sanitize any input data before storing it in session variables.

<?php
// Start the session
session_start();

// Check if the session variable exists before accessing it
if(isset($_SESSION['username'])) {
    $username = $_SESSION['username'];
    echo "Welcome back, $username!";
} else {
    echo "Please log in to access this page.";
}

// Sanitize input data before storing it in session variables
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$_SESSION['username'] = $username;
?>