How to Set Current Page "Active" in PHP Menus
Building a reusable menu.php file is a common pattern for maintaining consistent navigation across an application. However, one of the most persistent challenges is dynamically assigning the active class to the correct link. Without this visual cue, users cannot easily identify where they are within the site hierarchy, which degrades usability and accessibility.
The core problem isn't just about printing text; it's about comparing the current request context against a static list of links. In your specific case, you have a nested menu structure under Zeiten. To make "Ãffnungszeiten" active when visiting offnungszeiten.php, your PHP code needs to execute logic that determines which URL corresponds to the current session.
The Static vs. Dynamic Conflict
Your current snippet uses static HTML with hardcoded href attributes. If you simply wrap this in a PHP include, the page will render exactly as written every time, regardless of whether the user is on the Sauna page or the Beauty Lounge page.
To solve this, you must move the class assignment logic into the loop where the links are generated. The most robust approach involves comparing the requested path against the target paths defined in your menu.
You can achieve this by using PHP's basename() function to strip query parameters (like ?utm_source=google) and then performing a string comparison. Here is how you might structure the loop:
<?php
// Assume $current_page holds the filename of the current request
$current_page = basename($_SERVER['PHP_SELF']);
foreach ($menu_items as $item) {
// Compare only the file name to ignore query strings or trailing slashes
if ($current_page == $item['file']) {
echo '<li class="active">';
} else {
echo '<li>';
}
echo '<a href="' . $item['url'] . '">' . $item['label'] . '</a>';
// Close the li tag if we opened it above (simplified for clarity)
echo '</li>';
}
?>
In this pattern, the active class is applied only when the filename matches. This ensures that if a user visits frauensauna.php, the link with that specific URL receives the class, while others remain neutral.
Handling Nested Menus and Query Strings
Your example shows a dropdown menu under "Zeiten". When dealing with nested structures, you often need to check not just the current page, but also parent pages. For instance, if offnungszeiten.php is inside the zeiten folder, simply checking $current_page == 'offnungszeiten.php' works for that specific link.
However, a common pitfall occurs when URLs contain query parameters or when the base URL differs from the source code path. Using $_SERVER['REQUEST_URI'] and parsing it can be more flexible than relying solely on $_SERVER['PHP_SELF'], especially if your site uses a .htaccess rewrite rule to mask filenames (e.g., accessing /site/offnungszeiten instead of /site/offnungszeiten.php).
If you are working within the Laravel ecosystem, this problem is often solved by leveraging the framework's routing capabilities. Instead of manually parsing strings, you can access the route name or controller action directly. This allows you to bind the active state to a logical entity rather than a fragile file path string. You might see patterns like Route::current() or checking $request->route()->getName().
For more complex scenarios involving deep nesting where multiple parent links should light up simultaneously, you would need to traverse your menu tree recursively and mark ancestors of the current page as well. This adds complexity but improves navigation clarity for users exploring multi-level categories.
Why String Comparison Can Be Fragile
While string comparison is simple and effective for standard file-based routing, it breaks down quickly if you move toward more dynamic architectures. If a user accesses a page via a GET parameter (e.g., ?id=5) instead of a direct link, the filename check fails. In those cases, developers often rely on database-driven menus or configuration arrays that map route names to display labels and active states.
If you are maintaining a legacy site where refactoring to Laravel is not an option, stick to strict file-path comparisons but ensure your base_path or root directory handling is consistent. Always sanitize inputs if you are pulling menu links from external sources or user-generated content to prevent injection vulnerabilities.
Ultimately, the goal is to create a separation between data (the menu structure) and logic (the active state determination). By isolating the active check into a dedicated function or closure, your menu.php becomes easier to test and maintain without modifying the HTML template for every single page change.