What are common pitfalls when passing variables in PHP sessions?

Common pitfalls when passing variables in PHP sessions include not properly sanitizing the data before storing it, not checking if the variable exists before accessing it, and not unsetting the variable after it is no longer needed to avoid potential security risks.

// Example of properly passing and accessing a variable in PHP sessions

// Start the session
session_start();

// Set a variable in the session after sanitizing the data
$_SESSION['username'] = filter_var($_POST['username'], FILTER_SANITIZE_STRING);

// Check if the variable exists before accessing it
if(isset($_SESSION['username'])) {
    // Access the variable
    echo "Welcome, ".$_SESSION['username'];
}

// Unset the variable after it is no longer needed
unset($_SESSION['username']);