Skip to content
PHP Logo

How can access levels be managed dynamically in PHP, allowing users with different roles to access different pages without needing all levels simultaneously?

To manage access levels dynamically in PHP, you can use a session variable to store the user's role and then check this role against the required access level for each page. By doing this, users with different roles can access different pages without needing all levels simultaneously.

php
// Start the session
session_start();

// Set the user's role (you can retrieve this from a database or any other source)
$userRole = 'admin';

// Define access levels for each page
$accessLevels = [
    'admin' => ['admin_page.php', 'user_page.php'],
    'user' => ['user_page.php']
];

// Check if the user has access to the current page
$current_page = basename($_SERVER['PHP_SELF']);
if (!in_array($current_page, $accessLevels[$userRole])) {
    // Redirect the user to a different page or show an error message
    header('Location: unauthorized.php');
    exit;
}