This post was originally published thousands of years ago (well, at least 3).
The web is a fast paced environment and, as a result, the techniques explained here will probably be outdated.
You have been warned! :D.
The post is left here for posterity . ElanMan

Highlight Current Page Using PHP Includes

If you’re already using css to highlight the ‘current page’ in your navigation but then decide that you want to include your navigation using a PHP Include, a problem becomes apparent:

How do I apply a page specific class to an individual navigation link?

Fortunately, PHP has a useful predefined variable called $_SERVER[‘PHP_SELF’] which returns the path of our current page. Using this in conjunction with the strpos function, we can apply a dynamic class to the current link.


if (strpos($_SERVER['PHP_SELF'], 'about.php')) echo 'class="current"';

The function strpos() searches the path of our current page for the specified string, in our example, ‘about.php’. If it finds ‘about.php’, it writes ‘class=”current”‘ to the page. If it doesn’t find ‘about.php’, it returns FALSE and nothing gets written to the page.

Now, all we need to do is insert that code in to each navigation link inside our included file.

Included File

<ul id="navigation">
    <li><a <?php if (strpos($_SERVER['PHP_SELF'], 'index.php')) echo 'class="current"';?> href="index.php">Home Page</a></li>
    <li><a <?php if (strpos($_SERVER['PHP_SELF'], 'about.php')) echo 'class="current"';?> href="about.php">About Me</a></li>
    <li><a <?php if (strpos($_SERVER['PHP_SELF'], 'contact.php')) echo 'class="current"';?> href="contact.php">Contact Me</a></li>
    <li><a <?php if (strpos($_SERVER['PHP_SELF'], 'portfolio.php')) echo 'class="current"';?> href="portfolio.php">My Work</a></li>

The result is the current page link being assigned a class of current which can then be styled with your css:

.current {}

Similar Posts:


  • rocco

    Hello ElanMan,
    has been strpos deprecated in PHP 5.x or not? I’ve noticed that after PHP.4.x register_globals are again on, and maybe strpos shouldn’t be deprecated. What do you think about?

    Also please, if I have to apply class=”current” to the homepage – the index.php located in the web root of my server: /home/.sites/101/site1/web
    How can I do that?

    I’ve tried zillion ways, but unfortunately I’m not that good in PHP
    If I write the following for the homepage, each direcotry which contains and index.php lighten up:
    <a href=”/”>Home

    Anyway, your tutorial made my day. Thanks so much!

  • Brad Nagel

    Hi. Thank you for posting this, really saved my bacon. I was scouring the internet trying to get normal includes to work using the $thispage variable, but this solution is much more elegant. Thanks again.