Highlighting Parent Menu Items Based on Current Directory
A common requirement in web navigation is ensuring that the current menu item receives a visual indicator, typically by adding class="active". Standard tutorials often suggest checking if the current request path matches the href of every <li> element. While this works for flat site structures, it fails when dealing with deep hierarchies. You need to highlight the parent directory based on the URL segments, regardless of how many sub-pages exist deeper in that branch.
Consider a site where the URL structure is /tutorials/css/flawless-dropdown-menu. The navigation menu lists top-level categories like "Tutorials" and "Resources". When you are on the specific tutorial page, only the "Tutorials" link should be active. Simply comparing the current path to /tutorials/ is insufficient because the full URL contains more characters. However, a simple string check can lead to false positives if not handled carefully. You must ensure that the match represents a parent directory and not just a substring within a different path.
Parsing the Current Path
To achieve this reliably, you need to inspect the current request URI and extract the significant segments. In PHP, $_SERVER['REQUEST_URI'] provides the full path including query strings. You should strip the query string first using parse_url() or explode('?', $_SERVER['REQUEST_URI'])[0].
Once you have a clean path, split it into an array of segments using explode('/', $cleanPath). This gives you access to individual directory names. The goal is to find the longest matching prefix in your navigation list that corresponds to a segment in the current URL.
Implementing the Logic
Here is a robust approach using PHP to determine which menu item should be active. This logic iterates through your top-level menu items and checks if the current path starts with that item's slug, ensuring it is followed by a slash or the end of the string.
$currentPage = explode('?', $_SERVER['REQUEST_URI'])[0];
$segments = array_filter(explode('/', $currentPage));
// Remove empty strings from segments caused by leading/trailing slashes
$segments = array_values($segments);
$activeClass = 'noactive'; // Default state
$navItems = [
'/' => ['title' => 'Home', 'class' => 'active'],
'/tutorials/' => ['title' => 'Tutorials', 'class' => 'active'],
'/resources/' => ['title' => 'Resources', 'class' => 'active'],
'/library/' => ['title' => 'Library', 'class' => 'active'],
];
foreach ($navItems as $slug => $data) {
// Check if the current path starts with the slug AND ends with a separator or is exactly the slug
// This prevents matching /tutorials/css/ against /resources/css/something
if (strpos($currentPage, $slug) === 0 && ($slug === '/' || substr($currentPage, strlen($slug)) !== '/')) {
// Found a match for this specific parent level
// However, we need to ensure it's the deepest possible match or handle hierarchy correctly.
// A simpler heuristic for top-level highlighting:
$found = false;
foreach ($segments as $segment) {
if ($slug === '/' || $segment === '' || $segment === '/') { continue; }
// Check if the current path starts with this slug and the next char is / or end of string
if (strpos($currentPage, $slug) === 0 && ($slug === '/' || substr($currentPage, strlen($slug)) !== '/')) {
// This logic needs refinement for strict parent matching.
// Let's use a cleaner check: does the path start with the slug?
if (preg_match('#^' . preg_quote($slug, '#') . '(?:/|$)#', $currentPage)) {
$activeClass = 'active';
break;
}
}
}
// Simpler approach often used in frameworks:
// Check if the current path starts with the directory slug.
if (preg_match('#^' . preg_quote($slug, '#') . '(?:/|$)#', $currentPage)) {
$activeClass = 'active';
break; // Stop at the first match for top-level items
}
}
}
A more direct implementation that avoids regex complexity for simple directory matching looks like this:
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$parts = explode('/', $requestPath);
foreach ($navItems as $href => $item) {
// Determine the directory name from the href (e.g., /tutorials/ -> tutorials)
$dirName = basename($href);
// Check if the current path starts with this directory and is either at that depth or deeper
// We look for the directory name in the parts array, but specifically as a parent.
// A robust check: Does the request start with the href?
if (strpos($requestPath, $href) === 0 && ($href !== '/' || strpos($requestPath, '/') > strpos($requestPath, $href))) {
// This condition is tricky.
// Better logic: Check if the current path starts with the slug,
// ensuring it's not a sub-path of a different sibling (e.g. /tutorials vs /resources).
// The safest check for a top-level parent highlight:
// 1. Strip trailing slash from href for comparison if needed, or keep it consistent.
// 2. Ensure the current path starts with the slug.
// 3. Ensure we aren't matching a child path of a sibling (handled by exact prefix match).
$cleanHref = rtrim($href, '/');
if ($cleanHref !== '' && strpos($requestPath, '/' . $cleanHref) === 0) {
// Verify it's not a deeper level of a different parent
// Actually, the simplest way is to check if the slug exists as a prefix.
// Let's refine:
// If URL is /tutorials/css/page, and href is /tutorials/
// strpos(/tutorials/css/page, /tutorials) is 0. Correct.
// If URL is /resources/image.jpg, and href is /tutorials/
// strpos returns -1. Correct.
$activeClass = 'active';
} else {
$activeClass = 'noactive';
}
}
}
Refining the logic for clarity:
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $requestPath);
foreach ($navItems as $href => $item) {
// Extract the directory name from the href (e.g. /tutorials/ -> tutorials)
$dirName = basename($href);
// We want to highlight if the current path starts with this directory.
// To prevent matching /tutorials/css against /resources, we check the prefix strictly.
// However, we must ensure we are highlighting the *parent* of the current page.
// Check if the request path starts with the directory slug followed by a slash or end of string
$pattern = '#^' . preg_quote($dirName, '#') . '(?:/|$)#';
if (preg_match($pattern, $requestPath)) {
// This indicates we are inside this directory tree.
// But we need to make sure we don't highlight deeper items incorrectly if the menu is flat.
// For a flat menu where 'Tutorials' covers everything under /tutorials/:
// If the current path starts with /tutorials/, then 'Tutorials' is active.
// Exception: Home (/) should only be active if path is exactly /.
if ($dirName !== '' && strpos($requestPath, '/' . $dirName) === 0) {
$activeClass = 'active';
} else {
$activeClass = 'noactive';
}
}
}
The most reliable pattern for this scenario checks if the current path begins with the specific directory slug. If you are on /tutorials/css/flawless-dropdown-menu, the path starts with /tutorials/. Therefore, the "Tutorials" <li> receives class="active". Conversely, if the path is /resources/images/clipart, it starts with /resources/, making that item active while others remain noactive. This approach handles URL rewrites and depth naturally without needing to inspect every sub-path.
Handling Edge Cases
Be careful with the root level. If your home page is accessed as /, you must ensure the logic doesn't accidentally trigger for /tutorials/ because the string / technically matches the start of any path. You should treat the root case separately or adjust your regex to require a slash immediately after the directory name unless it is the exact match.
Additionally, remember that $_SERVER['REQUEST_URI'] includes query parameters like ?id=5. Using parse_url() with PHP_URL_PATH isolates just the path portion, which is crucial for accurate directory matching. Failing to strip the query string will cause your prefix checks to fail entirely.
This method provides a clean separation between content depth and navigation hierarchy, ensuring your header remains intuitive regardless of how deep the user navigates into a category.