-1

I got a problem. I use curPageUrl() function to locate the link to my file and use it as 'active' to get some CSS effects.

This is the curPageUrl() code:

function curPageURL() {
    $pageURL = 'http';
    if ($_SERVER['HTTPS'] == "on") {
        $pageURL .= "s";
    }
    $pageURL .= "://";
    if ($_SERVER['SERVER_PORT'] != "80") {
        $pageURL .= $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
    } else {
        $pageURL .= $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    }
    return $pageURL;
}

And this is my html code:

<a href='home.php'><li class="<?php if (curPageUrl() == 'http://something/home.php') {echo 'active';} ?>">Home</li></a>

But the problem begins when I start using $_GET[] method so the next link http://something/home.php?some_get_code is no more 'active'.

How can I concatenate everything after home.php so my link still be active?

2 Answers2

1

Use this:

<a href='home.php'>
    <li class="<?php if (strpos(curPageUrl(),'http://something/home.php') !== false) {echo 'active';} ?>">Home</li>
</a>

Use strpos function of PHP.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
0

You are digging in the wrong direction. The complete URL of a page can change in many ways: the query parameters, the script name or path, the server name; change any of them and the code will fail.

Try something more simple: compare home.php (not the full URL but only the script name) against basename($_SERVER['PHP_SELF']).

<a href='home.php'>
    <li class="<?php if (basename($_SERVER['PHP_SELF']) == 'home.php') {echo 'active';} ?>">Home</li>
</a>

The function basename() keeps only the file name from the path it receives as an argument (the part after the last /) while $_SERVER['PHP_SELF'] contains the path of the script that is invoke to process the current request.

This method has some weak points: if your site uses scripts located in multiple directories they must not have common names. More, if you need to rename 'home.php' for some reason, you must remember to also change the code above.

A better way is to set a variable in 'home.php' and check its value in the layout file:

// home.php
$page = 'home';
include 'view/home.php';


// view/home.php
<a href='home.php'>
    <li class="<?php if ($page == 'home') {echo 'active';} ?>">Home</li>
</a>

This way the mechanism is decoupled from URLs, server names, paths, file names or other external factors that can break it when they change.

axiac
  • 68,258
  • 9
  • 99
  • 134