如何用PHP为当前页面添加active类?解决前缀同名页面激活异常
Got it, let's sort out this annoying problem! The root cause here is that your current check using strpos($_SERVER['PHP_SELF'], 'csr') does a partial string match. Since csr-policy.php contains the substring "csr", the condition for the first nav item (CSR) will still evaluate to true when you're on the CSR Policy page—hence both items show as active.
Here are a few clean, reliable ways to fix this:
1. Exact Filename Match with basename()
The simplest approach is to compare the exact filename of the current page using basename(), which extracts just the filename from the full path in $_SERVER['PHP_SELF']:
<ul> <li><a href="csr.php" <?php if(basename($_SERVER['PHP_SELF']) === 'csr.php') {?> class="active" <?php }?>>CSR</a></li> <li><a href="csr-policy.php" <?php if(basename($_SERVER['PHP_SELF']) === 'csr-policy.php') {?> class="active" <?php }?>>CSR Policy</a></li> </ul>
This works because basename($_SERVER['PHP_SELF']) returns exactly csr.php when on that page, and csr-policy.php when on the policy page—no more partial matches causing confusion.
2. Regex for Precise Path Matching
If you prefer working with the full path, use a regular expression to match the exact end of the URL path:
<ul> <li><a href="csr.php" <?php if(preg_match('/\/csr\.php$/', $_SERVER['PHP_SELF'])) {?> class="active" <?php }?>>CSR</a></li> <li><a href="csr-policy.php" <?php if(preg_match('/\/csr-policy\.php$/', $_SERVER['PHP_SELF'])) {?> class="active" <?php }?>>CSR Policy</a></li> </ul>
The regex \/csr\.php$ ensures we're matching a path that ends with /csr.php (backslashes escape special characters like . and /). This guarantees we only target the exact page file.
3. Reusable Function for Cleaner Code
If you have more nav items to add later, wrapping the check in a reusable function keeps your code tidy:
<?php function isActivePage($targetFilename) { return basename($_SERVER['PHP_SELF']) === $targetFilename; } ?> <ul> <li><a href="csr.php" <?php if(isActivePage('csr.php')) {?> class="active" <?php }?>>CSR</a></li> <li><a href="csr-policy.php" <?php if(isActivePage('csr-policy.php')) {?> class="active" <?php }?>>CSR Policy</a></li> </ul>
Now you can just call isActivePage('your-page.php') for any new nav items without repeating the same logic each time.
内容的提问来源于stack exchange,提问作者Sneha Patel

