简体   繁体   中英

Working with PHP_SELF

Apologies for the bad title. I need a class to be added to an A tag depending on if the user is on respective page. So to clarify, here is the code:

<?php
 $basename = substr(strtolower(basename($_SERVER['PHP_SELF'])),0,strlen(basename($_SERVER['PHP_SELF']))-4);
?>

And then I use this code in the menu:

<li><a href="index.php"<?php if ($basename == 'index') { echo ' class="current"'; } ?>>Home</a></li>
<li><a href="about.php"<?php if ($basename == 'about') { echo ' class="current"'; } ?>>About</a></li>

As you can see, depending on if the user is on index.php or about.php, the class=current will be inserted. This works fine normally, but I am using this code in Wordpress where all the pages are this type of URL: index.php?page_id=X

So the about page URL is index.php?page_id=9, meaning that it will always input the class into the index one. Only solutions that I know of is that the $basename == 'index' can in anyway be full URL, eg $basename == 'index.php?page_id=X' but I couldnt make that work.

Help! Note that I am not experienced with PHP so any replies with detail would be appreciated!

the current file: __FILE__

the current folder of your file dirname(__FILE__).DIRECTORY_SEPARATOR // in 5.3: __DIR__

$page = $_GET[page_id]; 

我相信如果网址是?page_id = 9,这将返回例如9

Considering you're using Wordpress, I'd suggest that you make a variable towards the top of your page that determines that page's current location.

$path_parts = pathinfo($_SERVER['PHP_SELF']);

$current = strtolower($path_parts['filename']);

Then take that variable and set it in the <a></a> , as such:

<a <?php if($current == 'about') echo 'class="current"'; ?> href="#">About</a>

Or something like this, it's a start anyway.

additional information: http://php.net/manual/en/function.pathinfo.php

function GetFileName()
{
    $currentFile = basename($_SERVER["PHP_SELF"]);
    $parts = Explode('.', $currentFile);
    return $parts[0];
}
$basename = GetFileName();

<li>
    <a href="index.php" <?php if($basename =="index") echo "class='current'"; ?>>Home</a>
</li>
<li>
    <a href="about.php" <?php if($basename =="about") echo "class='current'"; ?>>About</a>
</li

>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM