使用php无效的活动当前页面

I have this code in header.php:

<?php

 $page = "";
?>

<ul class="nav navbar-nav navbar-right nav-pos">
   <li <?php if ($page == "home") { ?> class="active"<?php } ?>><a href="home.php">Home</a></li>
   <li <?php if($page == 'about') { ?> class="active"<?php } ?>><a href="aboutus.php">About us</a></li>
   <li <?php if($page == 'contact'){ ?> class="active"<?php } ?>><a href="contactus.php">Contact us</a></li>
   <li class="hidden-xs"><a href="#search"><i class="fa fa-search fa-rotate-90"></i></a></li>
</ul>

and on every page i put this code(and the name change depends on current page):

<?php include 'header.php';
  $page = 'about' ?>

and in css i made this:

.active{color:red }

But it is not working... any idea why?

Thank you for time, I really appreciate it

first you should remove $page = ""; from header

<?php
  $page = "";//remove this line in header file
?>

<ul class="nav navbar-nav navbar-right nav-pos">

Second in every page swap these two lines

<?php
   $page = 'about';//swap these lines
   include 'header.php' ;   
?>

some details: when header load then $page is empty and your conditions false in li tag. so, before header load you should assign value to $page

the best way: you should used $_SERVER['REQUEST_URI'] instead of hard coded $page. Example:

$url= explode('/',$_SERVER['REQUEST_URI']);
$page = end($request_array);//this show your_page.php
$page=preg_replace('"\.php$"', '', $page )//this will remove .php extension

The problem is that in your header.php you explicitly set $page = "" - which means none of the checks for $page == 'about'(etc) are passing.

Although you do set $page = 'about' in your main script, this is after the code in header.php has run, and its html output produced.

The solution is simple:

1) remove the $page = "" from header.php

2) set $page = "about" (or equivalent) before the include

You can do by using jQuery just adding this script in the footer section.

$(document).ready(function() {
    // get current URL path and assign 'active' class
    var pathname = window.location.pathname;
    $('.nav > li > a[href="'+pathname+'"]').parent().addClass('active');
});

In your case, this will work.

$(function(){
    var current = location.pathname;
    $('.nav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
});