Wesley Burden
Wesley Burden

Reputation: 137

What's the best way to get the Directory of a URL using php?

Im trying to set active classes in a nav using php. Now I need to set it by directory rather than complete URL as I have a main landing page for each directory with sub navigation for the other pages within the directory. I was going to use the following but this returns the full url.

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;}

 function activeLink($pageID) {
if ( $pageID == curPageURL() ) {
    echo 'class="active"';
} }

Then I call activeLink() in a nav item like this:

<li class="projectchild padding1"><a href="http://www.strangeleaves.com/nexus/index.php" <?php activelink('http://www.strangeleaves.com/nexus/index.php'); ?> >nexus</a></li>

Your suggestions on how to modify this to return the directory instead would be much appreciated.

Upvotes: 3

Views: 198

Answers (2)

numo16
numo16

Reputation: 1

You could get the full URL and then explode it to get down to your directory, like so:

$currentFile = $_SERVER["PHP_SELF"];
$parts = Explode('/', $currentFile);
$thisDir = $parts[count($parts) - 2];

Upvotes: 0

codaddict
codaddict

Reputation: 455440

If you want to extract the directory name from an URL you can use parse_url and dirname as:

$url = 'http://www.strangeleaves.com/nexus/index.php';
$arr = parse_url($url);
$path = dirname($arr['path']); // $path is now /nexus

Upvotes: 1

Related Questions