What are the best practices for storing session data in PHP, especially when comparing it with database values?

When storing session data in PHP, it is best practice to avoid storing sensitive information directly in the session variables. Instead, store a reference or identifier in the session and retrieve the corresponding data from the database when needed. This helps improve security by reducing the risk of exposing sensitive information if the session data is compromised.

// Store a reference to user data in session
$_SESSION['user_id'] = $user_id;

// Retrieve user data from database using the stored user_id
$query = "SELECT * FROM users WHERE id = :user_id";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':user_id', $_SESSION['user_id']);
$stmt->execute();
$user = $stmt->fetch();