Search code examples
phprequest-uri

navigation menu class active with php basename($_SERVER["REQUEST_URI"]


I have looked through all the questions here, but can't find the answer to this question.

I am sure it is a simple answer.

I have navigation menu, which is a PHP file and is included on each page.

I add a class active (I actually call it class current) using the following:

<a class="menu-nav <?php if (basename($_SERVER["REQUEST_URI"]) == '/past-events/index.php') echo "current";?>" href="http://website.com.au/past-events">PAST EVENTS</a>

This works fine for all the other pages because they are in the root directory, (actually with the other pages I use basename($_SERVER["SCRIPT_NAME"] ) but with the above page, because it is in the 'past-events' directory, it is not working.

I have tried:

<a class="menu-nav <?php if (basename($_SERVER["REQUEST_URI"]) == '/past-events/') echo "current";?>" href="http://website.com.au/past-events">PAST EVENTS</a>

but to no avail.

I should mention that the code is in a file called nav.php that lives in a foldr called 'includes' and is brought into each file that needs it using a php include

Can anyone see what I am doing wrong here?

Cheers, Al


Solution

  • Thank you all for your time and effort in trying to help me.

    I ended up adding:

    <?php print $_SERVER["REQUEST_URI"]; ?>
    

    to the page /past-events/index.php and found that it printed '/past-events/'

    so all I needed to do was get rid of the basename() and it worked fine:

    <a class="menu-nav <?php if ($_SERVER["REQUEST_URI"] == "/past-events/") echo "current";?>" href="http://website.com/past-events">PAST EVENTS</a>
    

    This will of course mean that all files in this directory will get class="current" but this suits my design just fine.

    Again, thank you for taking the time to help me. Cheers, Al.