Creating a Navigation Menu Based on User Roles
Start with a protected page
<?php
require __DIR__ . "/includes/require-login.php";
$username = $_SESSION["username"] ?? "user";
$role = $_SESSION["role"] ?? "user";
?>
Display navigation
<nav aria-label="Main navigation">
<ul>
<li><a href="dashboard.php">Dashboard</a></li>
<li><a href="results.php">Results</a></li>
<?php if ($role === "admin"): ?>
<li><a href="import.php">Import dataset</a></li>
<li><a href="manage-users.php">Manage users</a></li>
<?php endif; ?>
<li><a href="logout.php">Log out</a></li>
</ul>
</nav>
<p>
Signed in as
<?= htmlspecialchars($username, ENT_QUOTES, "UTF-8") ?>
</p>
Protect every destination
The condition only controls whether the link appears. import.php and every other administrator route must also require includes/require-admin.php.
Do not use JavaScript or CSS visibility as an access-control mechanism. Those technologies run in the user’s browser and can be changed.
Design guidance
- Use descriptive link text.
- Identify the current page with
aria-current="page". - Keep navigation order consistent.
- Do not display links that will always deny the current role.
- Provide a visible logout action.
- Ensure keyboard focus is clear in CSS.
Test
Compare logged-out, standard-user and administrator views. Then type each protected URL directly to verify that hidden links are not the only control.
Check
- Standard users see standard actions.
- Administrators see administrative actions.
- Every destination enforces access independently.
- Navigation is labelled and keyboard accessible.
- Session text is escaped.