How can session variables be used to restrict access to user-specific profile pages?

Session variables can be used to restrict access to user-specific profile pages by storing the user's unique identifier (such as their user ID) in a session variable when they log in. Then, on each profile page, you can check if the session variable matches the user ID associated with that page. If they do not match, you can redirect the user to a different page or display an error message.

<?php
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])) {
    // Check if user has access to this profile page
    if($_SESSION['user_id'] != $profile_user_id) {
        header("Location: unauthorized.php");
        exit();
    }
} else {
    header("Location: login.php");
    exit();
}
?>