How can PHP sessions be effectively used to determine the user currently logged in and retrieve their specific data?

To determine the user currently logged in and retrieve their specific data using PHP sessions, you can store the user's unique identifier (such as their user ID) in the session when they log in. Then, on subsequent pages, you can use this identifier to retrieve the user's data from the database and display it accordingly.

// Start the session
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])) {
    // Retrieve user data from the database using the user ID stored in the session
    $user_id = $_SESSION['user_id'];
    
    // Query the database to retrieve user data
    $query = "SELECT * FROM users WHERE id = $user_id";
    $result = mysqli_query($connection, $query);
    
    // Fetch user data
    $user = mysqli_fetch_assoc($result);
    
    // Display user data
    echo "Welcome back, " . $user['username'] . "!";
} else {
    echo "You are not logged in.";
}