What are some best practices for displaying user-specific content on a webpage using PHP session variables?

When displaying user-specific content on a webpage using PHP session variables, it is important to first check if the user is logged in and has the necessary session variables set. Once verified, you can then retrieve the user-specific data from the session and display it accordingly on the webpage.

<?php
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])) {
    // Retrieve user-specific data from session
    $username = $_SESSION['username'];
    $email = $_SESSION['email'];

    // Display user-specific content on the webpage
    echo "Welcome back, $username! Your email is $email.";
} else {
    echo "Please log in to view this content.";
}
?>