Skip to content
PHP Logo

How can PHP sessions be effectively used to control access to specific pages for different user roles?

To control access to specific pages for different user roles using PHP sessions, you can store the user's role in a session variable after they log in. Then, on each restricted page, check the user's role against the required role for that page. If the user's role does not match, redirect them to a different page.

php
// Start the session
session_start();

// Check if the user is logged in and their role is set
if(isset($_SESSION['role'])) {
    // Check if the user's role is allowed to access this page
    if($_SESSION['role'] != 'admin') {
        header("Location: unauthorized.php");
        exit;
    }
} else {
    header("Location: login.php");
    exit;
}