waubain
waubain

Reputation: 53

Dynamically change menu item in PHP

I know very little about PHP, but recently split the menu portion on my static web pages to a header.php and this works. I now want to change the font color of active page. I saw an example here but cannot get the php code to work. Here is my current menu before any changes

<div id="menu">
     <ul>
         <li><a href="index.php">Home</a></li>
         <li><a href="lessons.php">Lessons</a></li>
         <li><a href="contact.php">Contact</a></li>
     </ul>
</div> <!-- end menu div -->

I saw this code in StackOverflow (modified for my menu)

<?php # Using REQUEST_URI
$currentpage = $_SERVER['REQUEST_URI'];?>
<div class="nav">
    <div class="tab
         <?php
             if(preg_match("/index/i", $currentpage)||($currentpage=="/"))
                 echo " currentpage";
         ?>"><a href="index.php">Home</a>
     </div>
     <div class="tab
         <?php
             if(preg_match("/about/i", $currentpage))
                 echo " currentpage";
         ?>"><a href="lessons.php">Lessons</a>
     </div>
     <div class="tab
         <?php
             if(preg_match("/contact/i", $currentpage))
                 echo " currentpage";
         ?>"><a href="contact.php">Contact</a>
     </div>
 </div> <!--nav-->

When I tried to substitute the php between the ul and the /ul, I get an error message: line 2: Undefined Index: REQUEST_URI

I read about REQUEST_URI but do not understand why it is not working.

Any help would be appreciated. Thanks.

Upvotes: 0

Views: 1644

Answers (2)

waubain
waubain

Reputation: 53

I found another Q&A on this site similar to my question How add class='active' to html menu with php

I used the example provided by Toader Mihai Claudiu, although the last author preferred the approach I was trying to use. Since I am a novice and have a simple site for my students I went with Toader's approach and it worked. Maybe someday I will try the suggestion provided by Marcin

Thank you contributors.

Upvotes: 0

marcin_koss
marcin_koss

Reputation: 5882

To check available $_SERVER variables you can do <?php print_r($_SERVER) ?>

I heard that on IIS server REQUEST_URI will not be set. IF that's the case you can do the following...

http://davidwalsh.name/iis-php-server-request_uri

Upvotes: 1

Related Questions