How can PHP sessions be effectively used to control the display of specific pages on a website?

PHP sessions can be effectively used to control the display of specific pages on a website by storing a flag or variable in the session when a user logs in or performs a certain action. This flag can then be checked on each page to determine whether the user has the necessary permissions to view the content. By using PHP sessions in this way, you can easily restrict access to certain pages based on user roles or actions.

<?php
session_start();

// Check if user is logged in and has the necessary permission
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true && isset($_SESSION['admin']) && $_SESSION['admin'] == true) {
    // Display content for admin users
    echo "Welcome, admin!";
} else {
    // Redirect or display an error message
    header("Location: /login.php");
}
?>