How can PHP sessions be used to control user access and display different content based on login status?

To control user access and display different content based on login status, PHP sessions can be used to store and check the user's login status. By setting a session variable upon successful login and checking for its existence on protected pages, you can restrict access to certain content. This allows you to show different content to logged in users compared to non-logged in users.

session_start();

// Check if user is logged in
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true){
    // Display content for logged in users
    echo "Welcome, user!";
} else {
    // Display content for non-logged in users
    echo "Please log in to view this content.";
}