What are the potential pitfalls when trying to retrieve stored data from sessions in PHP?

Potential pitfalls when trying to retrieve stored data from sessions in PHP include not starting the session before trying to access session data, not checking if the session variable exists before accessing it, and not properly sanitizing and validating the retrieved data to prevent security vulnerabilities.

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

// Check if the session variable exists before accessing it
if(isset($_SESSION['user_id'])){
    $user_id = $_SESSION['user_id'];
    
    // Sanitize and validate the retrieved data
    $user_id = filter_var($user_id, FILTER_SANITIZE_NUMBER_INT);
    
    // Use the sanitized data
    echo "User ID: " . $user_id;
} else {
    echo "Session variable 'user_id' not set.";
}
?>